babylon.engine.ts 95 KB

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