babylon.engine.ts 88 KB

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