babylon.engine.ts 89 KB

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