babylon.engine.ts 93 KB

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