babylon.engine.ts 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206
  1. module BABYLON {
  2. export class _DepthCullingState {
  3. private _isDepthTestDirty = false;
  4. private _isDepthMaskDirty = false;
  5. private _isDepthFuncDirty = false;
  6. private _isCullFaceDirty = false;
  7. private _isCullDirty = false;
  8. private _depthTest: boolean;
  9. private _depthMask: boolean;
  10. private _depthFunc: number;
  11. private _cull: boolean;
  12. private _cullFace: number;
  13. public get isDirty(): boolean {
  14. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  15. }
  16. public get cullFace(): number {
  17. return this._cullFace;
  18. }
  19. public set cullFace(value: number) {
  20. if (this._cullFace === value) {
  21. return;
  22. }
  23. this._cullFace = value;
  24. this._isCullFaceDirty = true;
  25. }
  26. public get cull() {
  27. return this._cull;
  28. }
  29. public set cull(value: boolean) {
  30. if (this._cull === value) {
  31. return;
  32. }
  33. this._cull = value;
  34. this._isCullDirty = true;
  35. }
  36. public get depthFunc(): number {
  37. return this._depthFunc;
  38. }
  39. public set depthFunc(value: number) {
  40. if (this._depthFunc === value) {
  41. return;
  42. }
  43. this._depthFunc = value;
  44. this._isDepthFuncDirty = true;
  45. }
  46. public get depthMask(): boolean {
  47. return this._depthMask;
  48. }
  49. public set depthMask(value: boolean) {
  50. if (this._depthMask === value) {
  51. return;
  52. }
  53. this._depthMask = value;
  54. this._isDepthMaskDirty = true;
  55. }
  56. public get depthTest(): boolean {
  57. return this._depthTest;
  58. }
  59. public set depthTest(value: boolean) {
  60. if (this._depthTest === value) {
  61. return;
  62. }
  63. this._depthTest = value;
  64. this._isDepthTestDirty = true;
  65. }
  66. public reset() {
  67. this._depthMask = true;
  68. this._depthTest = true;
  69. this._depthFunc = null;
  70. this._cull = null;
  71. this._cullFace = null;
  72. this._isDepthTestDirty = true;
  73. this._isDepthMaskDirty = true;
  74. this._isDepthFuncDirty = false;
  75. this._isCullFaceDirty = false;
  76. this._isCullDirty = false;
  77. }
  78. public apply(gl: WebGLRenderingContext) {
  79. if (!this.isDirty) {
  80. return;
  81. }
  82. // Cull
  83. if (this._isCullDirty) {
  84. if (this.cull) {
  85. gl.enable(gl.CULL_FACE);
  86. } else {
  87. gl.disable(gl.CULL_FACE);
  88. }
  89. this._isCullDirty = false;
  90. }
  91. // Cull face
  92. if (this._isCullFaceDirty) {
  93. gl.cullFace(this.cullFace);
  94. this._isCullFaceDirty = false;
  95. }
  96. // Depth mask
  97. if (this._isDepthMaskDirty) {
  98. gl.depthMask(this.depthMask);
  99. this._isDepthMaskDirty = false;
  100. }
  101. // Depth test
  102. if (this._isDepthTestDirty) {
  103. if (this.depthTest) {
  104. gl.enable(gl.DEPTH_TEST);
  105. } else {
  106. gl.disable(gl.DEPTH_TEST);
  107. }
  108. this._isDepthTestDirty = false;
  109. }
  110. // Depth func
  111. if (this._isDepthFuncDirty) {
  112. gl.depthFunc(this.depthFunc);
  113. this._isDepthFuncDirty = false;
  114. }
  115. }
  116. }
  117. export class _AlphaState {
  118. private _isAlphaBlendDirty = false;
  119. private _isBlendFunctionParametersDirty = false;
  120. private _alphaBlend = false;
  121. private _blendFunctionParameters = new Array<number>(4);
  122. public get isDirty(): boolean {
  123. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  124. }
  125. public get alphaBlend(): boolean {
  126. return this._alphaBlend;
  127. }
  128. public set alphaBlend(value: boolean) {
  129. if (this._alphaBlend === value) {
  130. return;
  131. }
  132. this._alphaBlend = value;
  133. this._isAlphaBlendDirty = true;
  134. }
  135. public setAlphaBlendFunctionParameters(value0: number, value1: number, value2: number, value3: number): void {
  136. if (
  137. this._blendFunctionParameters[0] === value0 &&
  138. this._blendFunctionParameters[1] === value1 &&
  139. this._blendFunctionParameters[2] === value2 &&
  140. this._blendFunctionParameters[3] === value3
  141. ) {
  142. return;
  143. }
  144. this._blendFunctionParameters[0] = value0;
  145. this._blendFunctionParameters[1] = value1;
  146. this._blendFunctionParameters[2] = value2;
  147. this._blendFunctionParameters[3] = value3;
  148. this._isBlendFunctionParametersDirty = true;
  149. }
  150. public reset() {
  151. this._alphaBlend = false;
  152. this._blendFunctionParameters[0] = null;
  153. this._blendFunctionParameters[1] = null;
  154. this._blendFunctionParameters[2] = null;
  155. this._blendFunctionParameters[3] = null;
  156. this._isAlphaBlendDirty = true;
  157. this._isBlendFunctionParametersDirty = false;
  158. }
  159. public apply(gl: WebGLRenderingContext) {
  160. if (!this.isDirty) {
  161. return;
  162. }
  163. // Alpha blend
  164. if (this._isAlphaBlendDirty) {
  165. if (this._alphaBlend) {
  166. gl.enable(gl.BLEND);
  167. } else {
  168. gl.disable(gl.BLEND);
  169. }
  170. this._isAlphaBlendDirty = false;
  171. }
  172. // Alpha function
  173. if (this._isBlendFunctionParametersDirty) {
  174. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  175. this._isBlendFunctionParametersDirty = false;
  176. }
  177. }
  178. }
  179. var compileShader = (gl: WebGLRenderingContext, source: string, type: string, defines: string): WebGLShader => {
  180. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  181. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  182. gl.compileShader(shader);
  183. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  184. throw new Error(gl.getShaderInfoLog(shader));
  185. }
  186. return shader;
  187. };
  188. var getWebGLTextureType = (gl: WebGLRenderingContext, type: number): number => {
  189. var textureType = gl.UNSIGNED_BYTE;
  190. if (type === Engine.TEXTURETYPE_FLOAT)
  191. textureType = gl.FLOAT;
  192. return textureType;
  193. };
  194. var getSamplingParameters = (samplingMode: number, generateMipMaps: boolean, gl: WebGLRenderingContext): { min: number; mag: number } => {
  195. var magFilter = gl.NEAREST;
  196. var minFilter = gl.NEAREST;
  197. if (samplingMode === Texture.BILINEAR_SAMPLINGMODE) {
  198. magFilter = gl.LINEAR;
  199. if (generateMipMaps) {
  200. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  201. } else {
  202. minFilter = gl.LINEAR;
  203. }
  204. } else if (samplingMode === Texture.TRILINEAR_SAMPLINGMODE) {
  205. magFilter = gl.LINEAR;
  206. if (generateMipMaps) {
  207. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  208. } else {
  209. minFilter = gl.LINEAR;
  210. }
  211. } else if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  212. magFilter = gl.NEAREST;
  213. if (generateMipMaps) {
  214. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  215. } else {
  216. minFilter = gl.NEAREST;
  217. }
  218. }
  219. return {
  220. min: minFilter,
  221. mag: magFilter
  222. }
  223. }
  224. var prepareWebGLTexture = (texture: WebGLTexture, gl: WebGLRenderingContext, scene: Scene, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  225. processFunction: (width: number, height: number) => void, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE) => {
  226. var engine = scene.getEngine();
  227. var potWidth = Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  228. var potHeight = Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  229. gl.bindTexture(gl.TEXTURE_2D, texture);
  230. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  231. processFunction(potWidth, potHeight);
  232. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  233. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  234. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  235. if (!noMipmap && !isCompressed) {
  236. gl.generateMipmap(gl.TEXTURE_2D);
  237. }
  238. gl.bindTexture(gl.TEXTURE_2D, null);
  239. engine._activeTexturesCache = [];
  240. texture._baseWidth = width;
  241. texture._baseHeight = height;
  242. texture._width = potWidth;
  243. texture._height = potHeight;
  244. texture.isReady = true;
  245. texture.samplingMode = samplingMode;
  246. scene._removePendingData(texture);
  247. };
  248. var partialLoad = (url: string, index: number, loadedImages: any, scene,
  249. onfinish: (images: HTMLImageElement[]) => void) => {
  250. var onload = () => {
  251. loadedImages[index] = img;
  252. loadedImages._internalCount++;
  253. scene._removePendingData(img);
  254. if (loadedImages._internalCount === 6) {
  255. onfinish(loadedImages);
  256. }
  257. };
  258. var onerror = () => {
  259. scene._removePendingData(img);
  260. };
  261. var img = Tools.LoadImage(url, onload, onerror, scene.database);
  262. scene._addPendingData(img);
  263. }
  264. var cascadeLoad = (rootUrl: string, scene,
  265. onfinish: (images: HTMLImageElement[]) => void, extensions: string[]) => {
  266. var loadedImages: any = [];
  267. loadedImages._internalCount = 0;
  268. for (var index = 0; index < 6; index++) {
  269. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  270. }
  271. };
  272. export class EngineCapabilities {
  273. public maxTexturesImageUnits: number;
  274. public maxTextureSize: number;
  275. public maxCubemapTextureSize: number;
  276. public maxRenderTextureSize: number;
  277. public standardDerivatives: boolean;
  278. public s3tc;
  279. public textureFloat: boolean;
  280. public textureAnisotropicFilterExtension;
  281. public maxAnisotropy: number;
  282. public instancedArrays;
  283. public uintIndices: boolean;
  284. }
  285. /**
  286. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  287. */
  288. export class Engine {
  289. // Const statics
  290. private static _ALPHA_DISABLE = 0;
  291. private static _ALPHA_ADD = 1;
  292. private static _ALPHA_COMBINE = 2;
  293. private static _DELAYLOADSTATE_NONE = 0;
  294. private static _DELAYLOADSTATE_LOADED = 1;
  295. private static _DELAYLOADSTATE_LOADING = 2;
  296. private static _DELAYLOADSTATE_NOTLOADED = 4;
  297. private static _TEXTUREFORMAT_ALPHA = 0;
  298. private static _TEXTUREFORMAT_LUMINANCE = 1;
  299. private static _TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  300. private static _TEXTUREFORMAT_RGB = 4;
  301. private static _TEXTUREFORMAT_RGBA = 4;
  302. private static _TEXTURETYPE_UNSIGNED_INT = 0;
  303. private static _TEXTURETYPE_FLOAT = 1;
  304. public static get ALPHA_DISABLE(): number {
  305. return Engine._ALPHA_DISABLE;
  306. }
  307. public static get ALPHA_ADD(): number {
  308. return Engine._ALPHA_ADD;
  309. }
  310. public static get ALPHA_COMBINE(): number {
  311. return Engine._ALPHA_COMBINE;
  312. }
  313. public static get DELAYLOADSTATE_NONE(): number {
  314. return Engine._DELAYLOADSTATE_NONE;
  315. }
  316. public static get DELAYLOADSTATE_LOADED(): number {
  317. return Engine._DELAYLOADSTATE_LOADED;
  318. }
  319. public static get DELAYLOADSTATE_LOADING(): number {
  320. return Engine._DELAYLOADSTATE_LOADING;
  321. }
  322. public static get DELAYLOADSTATE_NOTLOADED(): number {
  323. return Engine._DELAYLOADSTATE_NOTLOADED;
  324. }
  325. public static get TEXTUREFORMAT_ALPHA(): number {
  326. return Engine._TEXTUREFORMAT_ALPHA;
  327. }
  328. public static get TEXTUREFORMAT_LUMINANCE(): number {
  329. return Engine._TEXTUREFORMAT_LUMINANCE;
  330. }
  331. public static get TEXTUREFORMAT_LUMINANCE_ALPHA(): number {
  332. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  333. }
  334. public static get TEXTUREFORMAT_RGB(): number {
  335. return Engine._TEXTUREFORMAT_RGB;
  336. }
  337. public static get TEXTUREFORMAT_RGBA(): number {
  338. return Engine._TEXTUREFORMAT_RGBA;
  339. }
  340. public static get TEXTURETYPE_UNSIGNED_INT(): number {
  341. return Engine._TEXTURETYPE_UNSIGNED_INT;
  342. }
  343. public static get TEXTURETYPE_FLOAT(): number {
  344. return Engine._TEXTURETYPE_FLOAT;
  345. }
  346. public static get Version(): string {
  347. return "2.1.0 alpha";
  348. }
  349. // Updatable statics so stick with vars here
  350. public static Epsilon = 0.001;
  351. public static CollisionsEpsilon = 0.001;
  352. public static ShadersRepository = "Babylon/Shaders/";
  353. // Public members
  354. public isFullscreen = false;
  355. public isPointerLock = false;
  356. public cullBackFaces = true;
  357. public renderEvenInBackground = true;
  358. public scenes = new Array<Scene>();
  359. // Private Members
  360. public _gl: WebGLRenderingContext;
  361. private _renderingCanvas: HTMLCanvasElement;
  362. private _windowIsBackground = false;
  363. public static audioEngine: AudioEngine;
  364. private _onBlur: () => void;
  365. private _onFocus: () => void;
  366. private _onFullscreenChange: () => void;
  367. private _onPointerLockChange: () => void;
  368. private _hardwareScalingLevel: number;
  369. private _caps: EngineCapabilities;
  370. private _pointerLockRequested: boolean;
  371. private _alphaTest: boolean;
  372. private _resizeLoadingUI: () => void;
  373. private _loadingDiv: HTMLDivElement;
  374. private _loadingTextDiv: HTMLDivElement;
  375. private _loadingDivBackgroundColor = "black";
  376. private _drawCalls = 0;
  377. private _glVersion: string;
  378. private _glRenderer: string;
  379. private _glVendor: string;
  380. private _renderingQueueLaunched = false;
  381. private _activeRenderLoops = [];
  382. // FPS
  383. private fpsRange = 60;
  384. private previousFramesDuration = [];
  385. private fps = 60;
  386. private deltaTime = 0;
  387. // States
  388. private _depthCullingState = new _DepthCullingState();
  389. private _alphaState = new _AlphaState();
  390. private _alphaMode = Engine.ALPHA_DISABLE;
  391. // Cache
  392. private _loadedTexturesCache = new Array<WebGLTexture>();
  393. public _activeTexturesCache = new Array<BaseTexture>();
  394. private _currentEffect: Effect;
  395. private _compiledEffects = {};
  396. private _vertexAttribArrays: boolean[];
  397. private _cachedViewport: Viewport;
  398. private _cachedVertexBuffers: any;
  399. private _cachedIndexBuffer: WebGLBuffer;
  400. private _cachedEffectForVertexBuffers: Effect;
  401. private _currentRenderTarget: WebGLTexture;
  402. private _canvasClientRect: ClientRect;
  403. private _uintIndicesCurrentlySet = false;
  404. private _workingCanvas: HTMLCanvasElement;
  405. private _workingContext: CanvasRenderingContext2D;
  406. /**
  407. * @constructor
  408. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  409. * @param {boolean} [antialias] - enable antialias
  410. * @param options - further options to be sent to the getContext function
  411. */
  412. constructor(canvas: HTMLCanvasElement, antialias?: boolean, options?) {
  413. this._renderingCanvas = canvas;
  414. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  415. options = options || {};
  416. options.antialias = antialias;
  417. // GL
  418. try {
  419. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  420. } catch (e) {
  421. throw new Error("WebGL not supported");
  422. }
  423. if (!this._gl) {
  424. throw new Error("WebGL not supported");
  425. }
  426. this._onBlur = () => {
  427. this._windowIsBackground = true;
  428. };
  429. this._onFocus = () => {
  430. this._windowIsBackground = false;
  431. };
  432. window.addEventListener("blur", this._onBlur);
  433. window.addEventListener("focus", this._onFocus);
  434. // Textures
  435. this._workingCanvas = document.createElement("canvas");
  436. this._workingContext = this._workingCanvas.getContext("2d");
  437. // Viewport
  438. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  439. this.resize();
  440. // Caps
  441. this._caps = new EngineCapabilities();
  442. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  443. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  444. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  445. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  446. // Infos
  447. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  448. var rendererInfo: any = this._gl.getExtension("WEBGL_debug_renderer_info");
  449. if (rendererInfo != null) {
  450. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  451. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  452. }
  453. if (!this._glVendor) {
  454. this._glVendor = "Unknown vendor";
  455. }
  456. if (!this._glRenderer) {
  457. this._glRenderer = "Unknown renderer";
  458. }
  459. // Extensions
  460. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  461. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  462. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  463. 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');
  464. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  465. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  466. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  467. // Depth buffer
  468. this.setDepthBuffer(true);
  469. this.setDepthFunctionToLessOrEqual();
  470. this.setDepthWrite(true);
  471. // Fullscreen
  472. this._onFullscreenChange = () => {
  473. if (document.fullscreen !== undefined) {
  474. this.isFullscreen = document.fullscreen;
  475. } else if (document.mozFullScreen !== undefined) {
  476. this.isFullscreen = document.mozFullScreen;
  477. } else if (document.webkitIsFullScreen !== undefined) {
  478. this.isFullscreen = document.webkitIsFullScreen;
  479. } else if (document.msIsFullScreen !== undefined) {
  480. this.isFullscreen = document.msIsFullScreen;
  481. }
  482. // Pointer lock
  483. if (this.isFullscreen && this._pointerLockRequested) {
  484. canvas.requestPointerLock = canvas.requestPointerLock ||
  485. canvas.msRequestPointerLock ||
  486. canvas.mozRequestPointerLock ||
  487. canvas.webkitRequestPointerLock;
  488. if (canvas.requestPointerLock) {
  489. canvas.requestPointerLock();
  490. }
  491. }
  492. };
  493. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  494. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  495. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  496. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  497. // Pointer lock
  498. this._onPointerLockChange = () => {
  499. this.isPointerLock = (document.mozPointerLockElement === canvas ||
  500. document.webkitPointerLockElement === canvas ||
  501. document.msPointerLockElement === canvas ||
  502. document.pointerLockElement === canvas
  503. );
  504. };
  505. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  506. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  507. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  508. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  509. if (!Engine.audioEngine) {
  510. Engine.audioEngine = new AudioEngine();
  511. }
  512. Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  513. }
  514. public getGlInfo() {
  515. return {
  516. vendor: this._glVendor,
  517. renderer: this._glRenderer,
  518. version: this._glVersion
  519. }
  520. }
  521. public getAspectRatio(camera: Camera): number {
  522. var viewport = camera.viewport;
  523. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  524. }
  525. public getRenderWidth(): number {
  526. if (this._currentRenderTarget) {
  527. return this._currentRenderTarget._width;
  528. }
  529. return this._renderingCanvas.width;
  530. }
  531. public getRenderHeight(): number {
  532. if (this._currentRenderTarget) {
  533. return this._currentRenderTarget._height;
  534. }
  535. return this._renderingCanvas.height;
  536. }
  537. public getRenderingCanvas(): HTMLCanvasElement {
  538. return this._renderingCanvas;
  539. }
  540. public getRenderingCanvasClientRect(): ClientRect {
  541. return this._renderingCanvas.getBoundingClientRect();
  542. }
  543. public setHardwareScalingLevel(level: number): void {
  544. this._hardwareScalingLevel = level;
  545. this.resize();
  546. }
  547. public getHardwareScalingLevel(): number {
  548. return this._hardwareScalingLevel;
  549. }
  550. public getLoadedTexturesCache(): WebGLTexture[] {
  551. return this._loadedTexturesCache;
  552. }
  553. public getCaps(): EngineCapabilities {
  554. return this._caps;
  555. }
  556. public get drawCalls(): number {
  557. return this._drawCalls;
  558. }
  559. // Methods
  560. public resetDrawCalls(): void {
  561. this._drawCalls = 0;
  562. }
  563. public setDepthFunctionToGreater(): void {
  564. this._depthCullingState.depthFunc = this._gl.GREATER;
  565. }
  566. public setDepthFunctionToGreaterOrEqual(): void {
  567. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  568. }
  569. public setDepthFunctionToLess(): void {
  570. this._depthCullingState.depthFunc = this._gl.LESS;
  571. }
  572. public setDepthFunctionToLessOrEqual(): void {
  573. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  574. }
  575. /**
  576. * stop executing a render loop function and remove it from the execution array
  577. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  578. */
  579. public stopRenderLoop(renderFunction?: () => void): void {
  580. if (!renderFunction) {
  581. this._activeRenderLoops = [];
  582. return;
  583. }
  584. var index = this._activeRenderLoops.indexOf(renderFunction);
  585. if (index >= 0) {
  586. this._activeRenderLoops.splice(index, 1);
  587. }
  588. }
  589. public _renderLoop(): void {
  590. var shouldRender = true;
  591. if (!this.renderEvenInBackground && this._windowIsBackground) {
  592. shouldRender = false;
  593. }
  594. if (shouldRender) {
  595. // Start new frame
  596. this.beginFrame();
  597. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  598. var renderFunction = this._activeRenderLoops[index];
  599. renderFunction();
  600. }
  601. // Present
  602. this.endFrame();
  603. }
  604. if (this._activeRenderLoops.length > 0) {
  605. // Register new frame
  606. Tools.QueueNewFrame(() => {
  607. this._renderLoop();
  608. });
  609. } else {
  610. this._renderingQueueLaunched = false;
  611. }
  612. }
  613. /**
  614. * Register and execute a render loop. The engine can have more than one render function.
  615. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  616. * @example
  617. * engine.runRenderLoop(function () {
  618. * scene.render()
  619. * })
  620. */
  621. public runRenderLoop(renderFunction: () => void): void {
  622. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  623. return;
  624. }
  625. this._activeRenderLoops.push(renderFunction);
  626. if (!this._renderingQueueLaunched) {
  627. this._renderingQueueLaunched = true;
  628. Tools.QueueNewFrame(() => {
  629. this._renderLoop();
  630. });
  631. }
  632. }
  633. /**
  634. * Toggle full screen mode.
  635. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  636. */
  637. public switchFullscreen(requestPointerLock: boolean): void {
  638. if (this.isFullscreen) {
  639. Tools.ExitFullscreen();
  640. } else {
  641. this._pointerLockRequested = requestPointerLock;
  642. Tools.RequestFullscreen(this._renderingCanvas);
  643. }
  644. }
  645. public clear(color: any, backBuffer: boolean, depthStencil: boolean): void {
  646. this.applyStates();
  647. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  648. if (this._depthCullingState.depthMask) {
  649. this._gl.clearDepth(1.0);
  650. }
  651. var mode = 0;
  652. if (backBuffer)
  653. mode |= this._gl.COLOR_BUFFER_BIT;
  654. if (depthStencil && this._depthCullingState.depthMask)
  655. mode |= this._gl.DEPTH_BUFFER_BIT;
  656. this._gl.clear(mode);
  657. }
  658. /**
  659. * Set the WebGL's viewport
  660. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  661. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  662. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  663. */
  664. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  665. var width = requiredWidth || this._renderingCanvas.width;
  666. var height = requiredHeight || this._renderingCanvas.height;
  667. var x = viewport.x || 0;
  668. var y = viewport.y || 0;
  669. this._cachedViewport = viewport;
  670. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  671. }
  672. public setDirectViewport(x: number, y: number, width: number, height: number): void {
  673. this._cachedViewport = null;
  674. this._gl.viewport(x, y, width, height);
  675. }
  676. public beginFrame(): void {
  677. this._measureFps();
  678. }
  679. public endFrame(): void {
  680. //this.flushFramebuffer();
  681. }
  682. /**
  683. * resize the view according to the canvas' size.
  684. * @example
  685. * window.addEventListener("resize", function () {
  686. * engine.resize();
  687. * });
  688. */
  689. public resize(): void {
  690. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  691. }
  692. /**
  693. * force a specific size of the canvas
  694. * @param {number} width - the new canvas' width
  695. * @param {number} height - the new canvas' height
  696. */
  697. public setSize(width: number, height: number): void {
  698. this._renderingCanvas.width = width;
  699. this._renderingCanvas.height = height;
  700. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  701. }
  702. public bindFramebuffer(texture: WebGLTexture): void {
  703. this._currentRenderTarget = texture;
  704. var gl = this._gl;
  705. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  706. this._gl.viewport(0, 0, texture._width, texture._height);
  707. this.wipeCaches();
  708. }
  709. public unBindFramebuffer(texture: WebGLTexture): void {
  710. this._currentRenderTarget = null;
  711. if (texture.generateMipMaps) {
  712. var gl = this._gl;
  713. gl.bindTexture(gl.TEXTURE_2D, texture);
  714. gl.generateMipmap(gl.TEXTURE_2D);
  715. gl.bindTexture(gl.TEXTURE_2D, null);
  716. }
  717. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  718. }
  719. public flushFramebuffer(): void {
  720. this._gl.flush();
  721. }
  722. public restoreDefaultFramebuffer(): void {
  723. this._currentRenderTarget = null;
  724. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  725. this.setViewport(this._cachedViewport);
  726. this.wipeCaches();
  727. }
  728. // VBOs
  729. private _resetVertexBufferBinding(): void {
  730. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  731. this._cachedVertexBuffers = null;
  732. }
  733. public createVertexBuffer(vertices: number[]): WebGLBuffer {
  734. var vbo = this._gl.createBuffer();
  735. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  736. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  737. this._resetVertexBufferBinding();
  738. vbo.references = 1;
  739. return vbo;
  740. }
  741. public createDynamicVertexBuffer(capacity: number): WebGLBuffer {
  742. var vbo = this._gl.createBuffer();
  743. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  744. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  745. this._resetVertexBufferBinding();
  746. vbo.references = 1;
  747. return vbo;
  748. }
  749. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: any, offset?: number): void {
  750. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  751. if (offset === undefined) {
  752. offset = 0;
  753. }
  754. if (vertices instanceof Float32Array) {
  755. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  756. } else {
  757. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  758. }
  759. this._resetVertexBufferBinding();
  760. }
  761. private _resetIndexBufferBinding(): void {
  762. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  763. this._cachedIndexBuffer = null;
  764. }
  765. public createIndexBuffer(indices: number[]): WebGLBuffer {
  766. var vbo = this._gl.createBuffer();
  767. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  768. // Check for 32 bits indices
  769. var arrayBuffer;
  770. var need32Bits = false;
  771. if (this._caps.uintIndices) {
  772. for (var index = 0; index < indices.length; index++) {
  773. if (indices[index] > 65535) {
  774. need32Bits = true;
  775. break;
  776. }
  777. }
  778. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  779. } else {
  780. arrayBuffer = new Uint16Array(indices);
  781. }
  782. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  783. this._resetIndexBufferBinding();
  784. vbo.references = 1;
  785. vbo.is32Bits = need32Bits;
  786. return vbo;
  787. }
  788. public bindBuffers(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  789. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  790. this._cachedVertexBuffers = vertexBuffer;
  791. this._cachedEffectForVertexBuffers = effect;
  792. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  793. var offset = 0;
  794. for (var index = 0; index < vertexDeclaration.length; index++) {
  795. var order = effect.getAttributeLocation(index);
  796. if (order >= 0) {
  797. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  798. }
  799. offset += vertexDeclaration[index] * 4;
  800. }
  801. }
  802. if (this._cachedIndexBuffer !== indexBuffer) {
  803. this._cachedIndexBuffer = indexBuffer;
  804. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  805. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  806. }
  807. }
  808. public bindMultiBuffers(vertexBuffers: VertexBuffer[], indexBuffer: WebGLBuffer, effect: Effect): void {
  809. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  810. this._cachedVertexBuffers = vertexBuffers;
  811. this._cachedEffectForVertexBuffers = effect;
  812. var attributes = effect.getAttributesNames();
  813. for (var index = 0; index < attributes.length; index++) {
  814. var order = effect.getAttributeLocation(index);
  815. if (order >= 0) {
  816. var vertexBuffer = vertexBuffers[attributes[index]];
  817. if (!vertexBuffer) {
  818. continue;
  819. }
  820. var stride = vertexBuffer.getStrideSize();
  821. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  822. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  823. }
  824. }
  825. }
  826. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  827. this._cachedIndexBuffer = indexBuffer;
  828. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  829. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  830. }
  831. }
  832. public _releaseBuffer(buffer: WebGLBuffer): boolean {
  833. buffer.references--;
  834. if (buffer.references === 0) {
  835. this._gl.deleteBuffer(buffer);
  836. return true;
  837. }
  838. return false;
  839. }
  840. public createInstancesBuffer(capacity: number): WebGLBuffer {
  841. var buffer = this._gl.createBuffer();
  842. buffer.capacity = capacity;
  843. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  844. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  845. return buffer;
  846. }
  847. public deleteInstancesBuffer(buffer: WebGLBuffer): void {
  848. this._gl.deleteBuffer(buffer);
  849. }
  850. public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[]): void {
  851. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  852. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  853. for (var index = 0; index < 4; index++) {
  854. var offsetLocation = offsetLocations[index];
  855. this._gl.enableVertexAttribArray(offsetLocation);
  856. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  857. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  858. }
  859. }
  860. public unBindInstancesBuffer(instancesBuffer: WebGLBuffer, offsetLocations: number[]): void {
  861. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  862. for (var index = 0; index < 4; index++) {
  863. var offsetLocation = offsetLocations[index];
  864. this._gl.disableVertexAttribArray(offsetLocation);
  865. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  866. }
  867. }
  868. public applyStates() {
  869. this._depthCullingState.apply(this._gl);
  870. this._alphaState.apply(this._gl);
  871. }
  872. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  873. // Apply states
  874. this.applyStates();
  875. this._drawCalls++;
  876. // Render
  877. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  878. if (instancesCount) {
  879. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  880. return;
  881. }
  882. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  883. }
  884. public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
  885. // Apply states
  886. this.applyStates();
  887. this._drawCalls++;
  888. if (instancesCount) {
  889. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  890. return;
  891. }
  892. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  893. }
  894. // Shaders
  895. public _releaseEffect(effect: Effect): void {
  896. if (this._compiledEffects[effect._key]) {
  897. delete this._compiledEffects[effect._key];
  898. if (effect.getProgram()) {
  899. this._gl.deleteProgram(effect.getProgram());
  900. }
  901. }
  902. }
  903. public createEffect(baseName: any, attributesNames: string[], uniformsNames: string[], samplers: string[], defines: string, fallbacks?: EffectFallbacks,
  904. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  905. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  906. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  907. var name = vertex + "+" + fragment + "@" + defines;
  908. if (this._compiledEffects[name]) {
  909. return this._compiledEffects[name];
  910. }
  911. var effect = new Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  912. effect._key = name;
  913. this._compiledEffects[name] = effect;
  914. return effect;
  915. }
  916. public createEffectForParticles(fragmentName: string, uniformsNames: string[]= [], samplers: string[]= [], defines = "", fallbacks?: EffectFallbacks,
  917. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  918. return this.createEffect(
  919. {
  920. vertex: "particles",
  921. fragmentElement: fragmentName
  922. },
  923. ["position", "color", "options"],
  924. ["view", "projection"].concat(uniformsNames),
  925. ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  926. }
  927. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: string): WebGLProgram {
  928. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  929. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  930. var shaderProgram = this._gl.createProgram();
  931. this._gl.attachShader(shaderProgram, vertexShader);
  932. this._gl.attachShader(shaderProgram, fragmentShader);
  933. this._gl.linkProgram(shaderProgram);
  934. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  935. if (!linked) {
  936. var error = this._gl.getProgramInfoLog(shaderProgram);
  937. if (error) {
  938. throw new Error(error);
  939. }
  940. }
  941. this._gl.deleteShader(vertexShader);
  942. this._gl.deleteShader(fragmentShader);
  943. return shaderProgram;
  944. }
  945. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): WebGLUniformLocation[] {
  946. var results = [];
  947. for (var index = 0; index < uniformsNames.length; index++) {
  948. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  949. }
  950. return results;
  951. }
  952. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  953. var results = [];
  954. for (var index = 0; index < attributesNames.length; index++) {
  955. try {
  956. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  957. } catch (e) {
  958. results.push(-1);
  959. }
  960. }
  961. return results;
  962. }
  963. public enableEffect(effect: Effect): void {
  964. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  965. if (effect && effect.onBind) {
  966. effect.onBind(effect);
  967. }
  968. return;
  969. }
  970. this._vertexAttribArrays = this._vertexAttribArrays || [];
  971. // Use program
  972. this._gl.useProgram(effect.getProgram());
  973. for (var i in this._vertexAttribArrays) {
  974. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  975. continue;
  976. }
  977. this._vertexAttribArrays[i] = false;
  978. this._gl.disableVertexAttribArray(i);
  979. }
  980. var attributesCount = effect.getAttributesCount();
  981. for (var index = 0; index < attributesCount; index++) {
  982. // Attributes
  983. var order = effect.getAttributeLocation(index);
  984. if (order >= 0) {
  985. this._vertexAttribArrays[order] = true;
  986. this._gl.enableVertexAttribArray(order);
  987. }
  988. }
  989. this._currentEffect = effect;
  990. if (effect.onBind) {
  991. effect.onBind(effect);
  992. }
  993. }
  994. public setArray(uniform: WebGLUniformLocation, array: number[]): void {
  995. if (!uniform)
  996. return;
  997. this._gl.uniform1fv(uniform, array);
  998. }
  999. public setArray2(uniform: WebGLUniformLocation, array: number[]): void {
  1000. if (!uniform || array.length % 2 !== 0)
  1001. return;
  1002. this._gl.uniform2fv(uniform, array);
  1003. }
  1004. public setArray3(uniform: WebGLUniformLocation, array: number[]): void {
  1005. if (!uniform || array.length % 3 !== 0)
  1006. return;
  1007. this._gl.uniform3fv(uniform, array);
  1008. }
  1009. public setArray4(uniform: WebGLUniformLocation, array: number[]): void {
  1010. if (!uniform || array.length % 4 !== 0)
  1011. return;
  1012. this._gl.uniform4fv(uniform, array);
  1013. }
  1014. public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void {
  1015. if (!uniform)
  1016. return;
  1017. this._gl.uniformMatrix4fv(uniform, false, matrices);
  1018. }
  1019. public setMatrix(uniform: WebGLUniformLocation, matrix: Matrix): void {
  1020. if (!uniform)
  1021. return;
  1022. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  1023. }
  1024. public setFloat(uniform: WebGLUniformLocation, value: number): void {
  1025. if (!uniform)
  1026. return;
  1027. this._gl.uniform1f(uniform, value);
  1028. }
  1029. public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void {
  1030. if (!uniform)
  1031. return;
  1032. this._gl.uniform2f(uniform, x, y);
  1033. }
  1034. public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void {
  1035. if (!uniform)
  1036. return;
  1037. this._gl.uniform3f(uniform, x, y, z);
  1038. }
  1039. public setBool(uniform: WebGLUniformLocation, bool: number): void {
  1040. if (!uniform)
  1041. return;
  1042. this._gl.uniform1i(uniform, bool);
  1043. }
  1044. public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void {
  1045. if (!uniform)
  1046. return;
  1047. this._gl.uniform4f(uniform, x, y, z, w);
  1048. }
  1049. public setColor3(uniform: WebGLUniformLocation, color3: Color3): void {
  1050. if (!uniform)
  1051. return;
  1052. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  1053. }
  1054. public setColor4(uniform: WebGLUniformLocation, color3: Color3, alpha: number): void {
  1055. if (!uniform)
  1056. return;
  1057. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  1058. }
  1059. // States
  1060. public setState(culling: boolean, force?: boolean): void {
  1061. // Culling
  1062. if (this._depthCullingState.cull !== culling || force) {
  1063. if (culling) {
  1064. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  1065. this._depthCullingState.cull = true;
  1066. } else {
  1067. this._depthCullingState.cull = false;
  1068. }
  1069. }
  1070. }
  1071. public setDepthBuffer(enable: boolean): void {
  1072. this._depthCullingState.depthTest = enable;
  1073. }
  1074. public getDepthWrite(): boolean {
  1075. return this._depthCullingState.depthMask;
  1076. }
  1077. public setDepthWrite(enable: boolean): void {
  1078. this._depthCullingState.depthMask = enable;
  1079. }
  1080. public setColorWrite(enable: boolean): void {
  1081. this._gl.colorMask(enable, enable, enable, enable);
  1082. }
  1083. public setAlphaMode(mode: number): void {
  1084. switch (mode) {
  1085. case Engine.ALPHA_DISABLE:
  1086. this.setDepthWrite(true);
  1087. this._alphaState.alphaBlend = false;
  1088. break;
  1089. case Engine.ALPHA_COMBINE:
  1090. this.setDepthWrite(false);
  1091. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  1092. this._alphaState.alphaBlend = true;
  1093. break;
  1094. case Engine.ALPHA_ADD:
  1095. this.setDepthWrite(false);
  1096. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1097. this._alphaState.alphaBlend = true;
  1098. break;
  1099. }
  1100. this._alphaMode = mode;
  1101. }
  1102. public getAlphaMode(): number {
  1103. return this._alphaMode;
  1104. }
  1105. public setAlphaTesting(enable: boolean): void {
  1106. this._alphaTest = enable;
  1107. }
  1108. public getAlphaTesting(): boolean {
  1109. return this._alphaTest;
  1110. }
  1111. // Textures
  1112. public wipeCaches(): void {
  1113. this._activeTexturesCache = [];
  1114. this._currentEffect = null;
  1115. this._depthCullingState.reset();
  1116. this._alphaState.reset();
  1117. this._cachedVertexBuffers = null;
  1118. this._cachedIndexBuffer = null;
  1119. this._cachedEffectForVertexBuffers = null;
  1120. }
  1121. public setSamplingMode(texture: WebGLTexture, samplingMode: number): void {
  1122. var gl = this._gl;
  1123. gl.bindTexture(gl.TEXTURE_2D, texture);
  1124. var magFilter = gl.NEAREST;
  1125. var minFilter = gl.NEAREST;
  1126. if (samplingMode === Texture.BILINEAR_SAMPLINGMODE) {
  1127. magFilter = gl.LINEAR;
  1128. minFilter = gl.LINEAR;
  1129. } else if (samplingMode === Texture.TRILINEAR_SAMPLINGMODE) {
  1130. magFilter = gl.LINEAR;
  1131. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  1132. }
  1133. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  1134. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  1135. gl.bindTexture(gl.TEXTURE_2D, null);
  1136. texture.samplingMode = samplingMode;
  1137. }
  1138. public createTexture(url: string, noMipmap: boolean, invertY: boolean, scene: Scene, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE, onLoad: () => void = null, onError: () => void = null, buffer: any = null): WebGLTexture {
  1139. var texture = this._gl.createTexture();
  1140. var extension: string;
  1141. var fromData: any = false;
  1142. if (url.substr(0, 5) === "data:") {
  1143. fromData = true;
  1144. }
  1145. if (!fromData)
  1146. extension = url.substr(url.length - 4, 4).toLowerCase();
  1147. else {
  1148. var oldUrl = url;
  1149. fromData = oldUrl.split(':');
  1150. url = oldUrl;
  1151. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  1152. }
  1153. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  1154. var isTGA = (extension === ".tga");
  1155. scene._addPendingData(texture);
  1156. texture.url = url;
  1157. texture.noMipmap = noMipmap;
  1158. texture.references = 1;
  1159. this._loadedTexturesCache.push(texture);
  1160. var onerror = () => {
  1161. scene._removePendingData(texture);
  1162. if (onError) {
  1163. onError();
  1164. }
  1165. };
  1166. if (isTGA) {
  1167. var callback = (arrayBuffer) => {
  1168. var data = new Uint8Array(arrayBuffer);
  1169. var header = Internals.TGATools.GetTGAHeader(data);
  1170. prepareWebGLTexture(texture, this._gl, scene, header.width, header.height, invertY, noMipmap, false, () => {
  1171. Internals.TGATools.UploadContent(this._gl, data);
  1172. if (onLoad) {
  1173. onLoad();
  1174. }
  1175. }, samplingMode);
  1176. };
  1177. if (!(fromData instanceof Array))
  1178. Tools.LoadFile(url, arrayBuffer => {
  1179. callback(arrayBuffer);
  1180. }, onerror, scene.database, true);
  1181. else
  1182. callback(buffer);
  1183. } else if (isDDS) {
  1184. callback = (data) => {
  1185. var info = Internals.DDSTools.GetDDSInfo(data);
  1186. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  1187. prepareWebGLTexture(texture, this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, () => {
  1188. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, info, loadMipmap, 1);
  1189. if (onLoad) {
  1190. onLoad();
  1191. }
  1192. }, samplingMode);
  1193. };
  1194. if (!(fromData instanceof Array))
  1195. Tools.LoadFile(url, data => {
  1196. callback(data);
  1197. }, onerror, scene.database, true);
  1198. else
  1199. callback(buffer);
  1200. } else {
  1201. var onload = (img) => {
  1202. prepareWebGLTexture(texture, this._gl, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight) => {
  1203. var isPot = (img.width === potWidth && img.height === potHeight);
  1204. if (!isPot) {
  1205. this._workingCanvas.width = potWidth;
  1206. this._workingCanvas.height = potHeight;
  1207. if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  1208. this._workingContext.imageSmoothingEnabled = false;
  1209. this._workingContext.mozImageSmoothingEnabled = false;
  1210. this._workingContext.oImageSmoothingEnabled = false;
  1211. this._workingContext.webkitImageSmoothingEnabled = false;
  1212. this._workingContext.msImageSmoothingEnabled = false;
  1213. }
  1214. this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  1215. if (samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  1216. this._workingContext.imageSmoothingEnabled = true;
  1217. this._workingContext.mozImageSmoothingEnabled = true;
  1218. this._workingContext.oImageSmoothingEnabled = true;
  1219. this._workingContext.webkitImageSmoothingEnabled = true;
  1220. this._workingContext.msImageSmoothingEnabled = true;
  1221. }
  1222. }
  1223. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, isPot ? img : this._workingCanvas);
  1224. if (onLoad) {
  1225. onLoad();
  1226. }
  1227. }, samplingMode);
  1228. };
  1229. if (!(fromData instanceof Array))
  1230. Tools.LoadImage(url, onload, onerror, scene.database);
  1231. else
  1232. Tools.LoadImage(buffer, onload, onerror, scene.database);
  1233. }
  1234. return texture;
  1235. }
  1236. public createRawTexture(data: ArrayBufferView, width: number, height: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number): WebGLTexture {
  1237. var texture = this._gl.createTexture();
  1238. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1239. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  1240. // Format
  1241. var internalFormat = this._gl.RGBA;
  1242. switch (format) {
  1243. case Engine.TEXTUREFORMAT_ALPHA:
  1244. internalFormat = this._gl.ALPHA;
  1245. break;
  1246. case Engine.TEXTUREFORMAT_LUMINANCE:
  1247. internalFormat = this._gl.LUMINANCE;
  1248. break;
  1249. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  1250. internalFormat = this._gl.LUMINANCE_ALPHA;
  1251. break;
  1252. case Engine.TEXTUREFORMAT_RGB:
  1253. internalFormat = this._gl.RGB;
  1254. break;
  1255. case Engine.TEXTUREFORMAT_RGBA:
  1256. internalFormat = this._gl.RGBA;
  1257. break;
  1258. }
  1259. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  1260. if (generateMipMaps) {
  1261. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1262. }
  1263. // Filters
  1264. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  1265. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1266. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1267. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1268. this._activeTexturesCache = [];
  1269. texture._baseWidth = width;
  1270. texture._baseHeight = height;
  1271. texture._width = width;
  1272. texture._height = height;
  1273. texture.isReady = true;
  1274. texture.references = 1;
  1275. texture.samplingMode = samplingMode;
  1276. this._loadedTexturesCache.push(texture);
  1277. return texture;
  1278. }
  1279. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number): WebGLTexture {
  1280. var texture = this._gl.createTexture();
  1281. width = Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  1282. height = Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  1283. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1284. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  1285. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1286. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1287. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1288. this._activeTexturesCache = [];
  1289. texture._baseWidth = width;
  1290. texture._baseHeight = height;
  1291. texture._width = width;
  1292. texture._height = height;
  1293. texture.isReady = false;
  1294. texture.generateMipMaps = generateMipMaps;
  1295. texture.references = 1;
  1296. texture.samplingMode = samplingMode;
  1297. this._loadedTexturesCache.push(texture);
  1298. return texture;
  1299. }
  1300. public updateDynamicTexture(texture: WebGLTexture, canvas: HTMLCanvasElement, invertY: boolean): void {
  1301. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1302. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  1303. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  1304. if (texture.generateMipMaps) {
  1305. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1306. }
  1307. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1308. this._activeTexturesCache = [];
  1309. texture.isReady = true;
  1310. }
  1311. public updateVideoTexture(texture: WebGLTexture, video: HTMLVideoElement, invertY: boolean): void {
  1312. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1313. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  1314. // Scale the video if it is a NPOT using the current working canvas
  1315. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  1316. if (!texture._workingCanvas) {
  1317. texture._workingCanvas = document.createElement("canvas");
  1318. texture._workingContext = texture._workingCanvas.getContext("2d");
  1319. texture._workingCanvas.width = texture._width;
  1320. texture._workingCanvas.height = texture._height;
  1321. }
  1322. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  1323. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  1324. } else {
  1325. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  1326. }
  1327. if (texture.generateMipMaps) {
  1328. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1329. }
  1330. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1331. this._activeTexturesCache = [];
  1332. texture.isReady = true;
  1333. }
  1334. public createRenderTargetTexture(size: any, options): WebGLTexture {
  1335. // old version had a "generateMipMaps" arg instead of options.
  1336. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  1337. // in the same way, generateDepthBuffer is defaulted to true
  1338. var generateMipMaps = false;
  1339. var generateDepthBuffer = true;
  1340. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  1341. var samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  1342. if (options !== undefined) {
  1343. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  1344. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  1345. type = options.type === undefined ? type : options.type;
  1346. if (options.samplingMode !== undefined) {
  1347. samplingMode = options.samplingMode;
  1348. }
  1349. if (type === Engine.TEXTURETYPE_FLOAT) {
  1350. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  1351. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  1352. }
  1353. }
  1354. var gl = this._gl;
  1355. var texture = gl.createTexture();
  1356. gl.bindTexture(gl.TEXTURE_2D, texture);
  1357. var width = size.width || size;
  1358. var height = size.height || size;
  1359. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  1360. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  1361. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  1362. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  1363. }
  1364. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  1365. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  1366. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1367. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1368. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  1369. var depthBuffer: WebGLRenderbuffer;
  1370. // Create the depth buffer
  1371. if (generateDepthBuffer) {
  1372. depthBuffer = gl.createRenderbuffer();
  1373. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  1374. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  1375. }
  1376. // Create the framebuffer
  1377. var framebuffer = gl.createFramebuffer();
  1378. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  1379. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  1380. if (generateDepthBuffer) {
  1381. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  1382. }
  1383. // Unbind
  1384. gl.bindTexture(gl.TEXTURE_2D, null);
  1385. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  1386. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  1387. texture._framebuffer = framebuffer;
  1388. if (generateDepthBuffer) {
  1389. texture._depthBuffer = depthBuffer;
  1390. }
  1391. texture._width = width;
  1392. texture._height = height;
  1393. texture.isReady = true;
  1394. texture.generateMipMaps = generateMipMaps;
  1395. texture.references = 1;
  1396. texture.samplingMode = samplingMode;
  1397. this._activeTexturesCache = [];
  1398. this._loadedTexturesCache.push(texture);
  1399. return texture;
  1400. }
  1401. public createCubeTexture(rootUrl: string, scene: Scene, extensions: string[], noMipmap?: boolean): WebGLTexture {
  1402. var gl = this._gl;
  1403. var texture = gl.createTexture();
  1404. texture.isCube = true;
  1405. texture.url = rootUrl;
  1406. texture.references = 1;
  1407. this._loadedTexturesCache.push(texture);
  1408. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  1409. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  1410. if (isDDS) {
  1411. Tools.LoadFile(rootUrl, data => {
  1412. var info = Internals.DDSTools.GetDDSInfo(data);
  1413. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  1414. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1415. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  1416. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, info, loadMipmap, 6);
  1417. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  1418. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1419. }
  1420. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1421. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  1422. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1423. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1424. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1425. this._activeTexturesCache = [];
  1426. texture._width = info.width;
  1427. texture._height = info.height;
  1428. texture.isReady = true;
  1429. }, null, null, true);
  1430. } else {
  1431. cascadeLoad(rootUrl, scene, imgs => {
  1432. var width = Tools.GetExponantOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize);
  1433. var height = width;
  1434. this._workingCanvas.width = width;
  1435. this._workingCanvas.height = height;
  1436. var faces = [
  1437. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  1438. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  1439. ];
  1440. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1441. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  1442. for (var index = 0; index < faces.length; index++) {
  1443. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  1444. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._workingCanvas);
  1445. }
  1446. if (!noMipmap) {
  1447. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1448. }
  1449. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1450. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  1451. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1452. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1453. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1454. this._activeTexturesCache = [];
  1455. texture._width = width;
  1456. texture._height = height;
  1457. texture.isReady = true;
  1458. }, extensions);
  1459. }
  1460. return texture;
  1461. }
  1462. public _releaseTexture(texture: WebGLTexture): void {
  1463. var gl = this._gl;
  1464. if (texture._framebuffer) {
  1465. gl.deleteFramebuffer(texture._framebuffer);
  1466. }
  1467. if (texture._depthBuffer) {
  1468. gl.deleteRenderbuffer(texture._depthBuffer);
  1469. }
  1470. gl.deleteTexture(texture);
  1471. // Unbind channels
  1472. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  1473. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1474. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1475. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1476. this._activeTexturesCache[channel] = null;
  1477. }
  1478. var index = this._loadedTexturesCache.indexOf(texture);
  1479. if (index !== -1) {
  1480. this._loadedTexturesCache.splice(index, 1);
  1481. }
  1482. }
  1483. public bindSamplers(effect: Effect): void {
  1484. this._gl.useProgram(effect.getProgram());
  1485. var samplers = effect.getSamplers();
  1486. for (var index = 0; index < samplers.length; index++) {
  1487. var uniform = effect.getUniform(samplers[index]);
  1488. this._gl.uniform1i(uniform, index);
  1489. }
  1490. this._currentEffect = null;
  1491. }
  1492. public _bindTexture(channel: number, texture: WebGLTexture): void {
  1493. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1494. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1495. this._activeTexturesCache[channel] = null;
  1496. }
  1497. public setTextureFromPostProcess(channel: number, postProcess: PostProcess): void {
  1498. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  1499. }
  1500. public setTexture(channel: number, texture: BaseTexture): void {
  1501. if (channel < 0) {
  1502. return;
  1503. }
  1504. // Not ready?
  1505. if (!texture || !texture.isReady()) {
  1506. if (this._activeTexturesCache[channel] != null) {
  1507. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1508. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1509. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1510. this._activeTexturesCache[channel] = null;
  1511. }
  1512. return;
  1513. }
  1514. // Video
  1515. if (texture instanceof VideoTexture) {
  1516. if ((<VideoTexture>texture).update()) {
  1517. this._activeTexturesCache[channel] = null;
  1518. }
  1519. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  1520. texture.delayLoad();
  1521. return;
  1522. }
  1523. if (this._activeTexturesCache[channel] === texture) {
  1524. return;
  1525. }
  1526. this._activeTexturesCache[channel] = texture;
  1527. var internalTexture = texture.getInternalTexture();
  1528. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1529. if (internalTexture.isCube) {
  1530. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  1531. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  1532. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  1533. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  1534. var textureWrapMode = (texture.coordinatesMode !== Texture.CUBIC_MODE && texture.coordinatesMode !== Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  1535. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  1536. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  1537. }
  1538. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  1539. } else {
  1540. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  1541. if (internalTexture._cachedWrapU !== texture.wrapU) {
  1542. internalTexture._cachedWrapU = texture.wrapU;
  1543. switch (texture.wrapU) {
  1544. case Texture.WRAP_ADDRESSMODE:
  1545. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  1546. break;
  1547. case Texture.CLAMP_ADDRESSMODE:
  1548. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  1549. break;
  1550. case Texture.MIRROR_ADDRESSMODE:
  1551. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  1552. break;
  1553. }
  1554. }
  1555. if (internalTexture._cachedWrapV !== texture.wrapV) {
  1556. internalTexture._cachedWrapV = texture.wrapV;
  1557. switch (texture.wrapV) {
  1558. case Texture.WRAP_ADDRESSMODE:
  1559. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  1560. break;
  1561. case Texture.CLAMP_ADDRESSMODE:
  1562. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  1563. break;
  1564. case Texture.MIRROR_ADDRESSMODE:
  1565. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  1566. break;
  1567. }
  1568. }
  1569. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  1570. }
  1571. }
  1572. public _setAnisotropicLevel(key: number, texture: BaseTexture) {
  1573. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  1574. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  1575. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  1576. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  1577. }
  1578. }
  1579. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  1580. var data = new Uint8Array(height * width * 4);
  1581. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  1582. return data;
  1583. }
  1584. // Dispose
  1585. public dispose(): void {
  1586. this.hideLoadingUI();
  1587. this.stopRenderLoop();
  1588. // Release scenes
  1589. while (this.scenes.length) {
  1590. this.scenes[0].dispose();
  1591. }
  1592. // Release audio engine
  1593. Engine.audioEngine.dispose();
  1594. // Release effects
  1595. for (var name in this._compiledEffects) {
  1596. this._gl.deleteProgram(this._compiledEffects[name]._program);
  1597. }
  1598. // Unbind
  1599. for (var i in this._vertexAttribArrays) {
  1600. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  1601. continue;
  1602. }
  1603. this._gl.disableVertexAttribArray(i);
  1604. }
  1605. // Events
  1606. window.removeEventListener("blur", this._onBlur);
  1607. window.removeEventListener("focus", this._onFocus);
  1608. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  1609. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  1610. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  1611. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  1612. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  1613. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  1614. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  1615. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  1616. }
  1617. // Loading screen
  1618. public displayLoadingUI(): void {
  1619. this._loadingDiv = document.createElement("div");
  1620. this._loadingDiv.style.opacity = "0";
  1621. this._loadingDiv.style.transition = "opacity 1.5s ease";
  1622. // Loading text
  1623. this._loadingTextDiv = document.createElement("div");
  1624. this._loadingTextDiv.style.position = "absolute";
  1625. this._loadingTextDiv.style.left = "0";
  1626. this._loadingTextDiv.style.top = "50%";
  1627. this._loadingTextDiv.style.marginTop = "80px";
  1628. this._loadingTextDiv.style.width = "100%";
  1629. this._loadingTextDiv.style.height = "20px";
  1630. this._loadingTextDiv.style.fontFamily = "Arial";
  1631. this._loadingTextDiv.style.fontSize = "14px";
  1632. this._loadingTextDiv.style.color = "white";
  1633. this._loadingTextDiv.style.textAlign = "center";
  1634. this._loadingTextDiv.innerHTML = "Loading";
  1635. this._loadingDiv.appendChild(this._loadingTextDiv);
  1636. // Loading img
  1637. var imgBack = new Image();
  1638. 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==";
  1639. imgBack.style.position = "absolute";
  1640. imgBack.style.left = "50%";
  1641. imgBack.style.top = "50%";
  1642. imgBack.style.marginLeft = "-50px";
  1643. imgBack.style.marginTop = "-50px";
  1644. imgBack.style.transition = "transform 1.0s ease";
  1645. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  1646. var deg = 360;
  1647. var onTransitionEnd = () => {
  1648. deg += 360;
  1649. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  1650. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  1651. }
  1652. imgBack.addEventListener("transitionend", onTransitionEnd);
  1653. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  1654. this._loadingDiv.appendChild(imgBack);
  1655. // front image
  1656. var imgFront = new Image();
  1657. 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=";
  1658. imgFront.style.position = "absolute";
  1659. imgFront.style.left = "50%";
  1660. imgFront.style.top = "50%";
  1661. imgFront.style.marginLeft = "-50px";
  1662. imgFront.style.marginTop = "-50px";
  1663. this._loadingDiv.appendChild(imgFront);
  1664. // Resize
  1665. this._resizeLoadingUI = () => {
  1666. var canvasRect = this.getRenderingCanvasClientRect();
  1667. this._loadingDiv.style.position = "absolute";
  1668. this._loadingDiv.style.left = canvasRect.left + "px";
  1669. this._loadingDiv.style.top = canvasRect.top + "px";
  1670. this._loadingDiv.style.width = canvasRect.width + "px";
  1671. this._loadingDiv.style.height = canvasRect.height + "px";
  1672. }
  1673. this._resizeLoadingUI();
  1674. window.addEventListener("resize", this._resizeLoadingUI);
  1675. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  1676. document.body.appendChild(this._loadingDiv);
  1677. setTimeout(() => {
  1678. this._loadingDiv.style.opacity = "1";
  1679. imgBack.style.transform = "rotateZ(360deg)";
  1680. imgBack.style.webkitTransform = "rotateZ(360deg)";
  1681. }, 0);
  1682. }
  1683. public set loadingUIText(text: string) {
  1684. if (!this._loadingDiv) {
  1685. return;
  1686. }
  1687. this._loadingTextDiv.innerHTML = text;
  1688. }
  1689. public get loadingUIBackgroundColor(): string {
  1690. return this._loadingDivBackgroundColor;
  1691. }
  1692. public set loadingUIBackgroundColor(color: string) {
  1693. this._loadingDivBackgroundColor = color;
  1694. if (!this._loadingDiv) {
  1695. return;
  1696. }
  1697. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  1698. }
  1699. public hideLoadingUI(): void {
  1700. if (!this._loadingDiv) {
  1701. return;
  1702. }
  1703. var onTransitionEnd = () => {
  1704. if (!this._loadingDiv) {
  1705. return;
  1706. }
  1707. document.body.removeChild(this._loadingDiv);
  1708. window.removeEventListener("resize", this._resizeLoadingUI);
  1709. this._loadingDiv = null;
  1710. }
  1711. this._loadingDiv.style.opacity = "0";
  1712. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  1713. }
  1714. // FPS
  1715. public getFps(): number {
  1716. return this.fps;
  1717. }
  1718. public getDeltaTime(): number {
  1719. return this.deltaTime;
  1720. }
  1721. private _measureFps(): void {
  1722. this.previousFramesDuration.push(Tools.Now);
  1723. var length = this.previousFramesDuration.length;
  1724. if (length >= 2) {
  1725. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  1726. }
  1727. if (length >= this.fpsRange) {
  1728. if (length > this.fpsRange) {
  1729. this.previousFramesDuration.splice(0, 1);
  1730. length = this.previousFramesDuration.length;
  1731. }
  1732. var sum = 0;
  1733. for (var id = 0; id < length - 1; id++) {
  1734. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  1735. }
  1736. this.fps = 1000.0 / (sum / (length - 1));
  1737. }
  1738. }
  1739. // Statics
  1740. public static isSupported(): boolean {
  1741. try {
  1742. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  1743. if (navigator.isCocoonJS) {
  1744. return true;
  1745. }
  1746. var tempcanvas = document.createElement("canvas");
  1747. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  1748. return gl != null && !!window.WebGLRenderingContext;
  1749. } catch (e) {
  1750. return false;
  1751. }
  1752. }
  1753. }
  1754. }