babylon.engine.ts 88 KB

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