babylon.engine.ts 89 KB

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