babylon.engine.ts 92 KB

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