babylon.engine.ts 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929
  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 _depthTest: boolean;
  9. private _depthMask: boolean;
  10. private _depthFunc: number;
  11. private _cull: boolean;
  12. private _cullFace: number;
  13. public get isDirty(): boolean {
  14. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  15. }
  16. public get cullFace(): number {
  17. return this._cullFace;
  18. }
  19. public set cullFace(value: number) {
  20. if (this._cullFace === value) {
  21. return;
  22. }
  23. this._cullFace = value;
  24. this._isCullFaceDirty = true;
  25. }
  26. public get cull() {
  27. return this._cull;
  28. }
  29. public set cull(value: boolean) {
  30. if (this._cull === value) {
  31. return;
  32. }
  33. this._cull = value;
  34. this._isCullDirty = true;
  35. }
  36. public get depthFunc(): number {
  37. return this._depthFunc;
  38. }
  39. public set depthFunc(value: number) {
  40. if (this._depthFunc === value) {
  41. return;
  42. }
  43. this._depthFunc = value;
  44. this._isDepthFuncDirty = true;
  45. }
  46. public get depthMask(): boolean {
  47. return this._depthMask;
  48. }
  49. public set depthMask(value: boolean) {
  50. if (this._depthMask === value) {
  51. return;
  52. }
  53. this._depthMask = value;
  54. this._isDepthMaskDirty = true;
  55. }
  56. public get depthTest(): boolean {
  57. return this._depthTest;
  58. }
  59. public set depthTest(value: boolean) {
  60. if (this._depthTest === value) {
  61. return;
  62. }
  63. this._depthTest = value;
  64. this._isDepthTestDirty = true;
  65. }
  66. public reset() {
  67. this._depthMask = true;
  68. this._depthTest = true;
  69. this._depthFunc = null;
  70. this._cull = null;
  71. this._cullFace = null;
  72. this._isDepthTestDirty = true;
  73. this._isDepthMaskDirty = true;
  74. this._isDepthFuncDirty = false;
  75. this._isCullFaceDirty = false;
  76. this._isCullDirty = false;
  77. }
  78. public apply(gl: WebGLRenderingContext) {
  79. if (!this.isDirty) {
  80. return;
  81. }
  82. // Cull
  83. if (this._isCullDirty) {
  84. if (this.cull === true) {
  85. gl.enable(gl.CULL_FACE);
  86. } else if (this.cull === false) {
  87. gl.disable(gl.CULL_FACE);
  88. }
  89. this._isCullDirty = false;
  90. }
  91. // Cull face
  92. if (this._isCullFaceDirty) {
  93. gl.cullFace(this.cullFace);
  94. this._isCullFaceDirty = false;
  95. }
  96. // Depth mask
  97. if (this._isDepthMaskDirty) {
  98. gl.depthMask(this.depthMask);
  99. this._isDepthMaskDirty = false;
  100. }
  101. // Depth test
  102. if (this._isDepthTestDirty) {
  103. if (this.depthTest === true) {
  104. gl.enable(gl.DEPTH_TEST);
  105. } else if (this.depthTest === false) {
  106. gl.disable(gl.DEPTH_TEST);
  107. }
  108. this._isDepthTestDirty = false;
  109. }
  110. // Depth func
  111. if (this._isDepthFuncDirty) {
  112. gl.depthFunc(this.depthFunc);
  113. this._isDepthFuncDirty = false;
  114. }
  115. }
  116. }
  117. export class _AlphaState {
  118. private _isAlphaBlendDirty = false;
  119. private _isBlendFunctionParametersDirty = false;
  120. private _alphaBlend = false;
  121. private _blendFunctionParameters = new Array<number>(4);
  122. public get isDirty(): boolean {
  123. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  124. }
  125. public get alphaBlend(): boolean {
  126. return this._alphaBlend;
  127. }
  128. public set alphaBlend(value: boolean) {
  129. if (this._alphaBlend === value) {
  130. return;
  131. }
  132. this._alphaBlend = value;
  133. this._isAlphaBlendDirty = true;
  134. }
  135. public setAlphaBlendFunctionParameters(value0: number, value1: number, value2: number, value3: number): void {
  136. if (
  137. this._blendFunctionParameters[0] === value0 &&
  138. this._blendFunctionParameters[1] === value1 &&
  139. this._blendFunctionParameters[2] === value2 &&
  140. this._blendFunctionParameters[3] === value3
  141. ) {
  142. return;
  143. }
  144. this._blendFunctionParameters[0] = value0;
  145. this._blendFunctionParameters[1] = value1;
  146. this._blendFunctionParameters[2] = value2;
  147. this._blendFunctionParameters[3] = value3;
  148. this._isBlendFunctionParametersDirty = true;
  149. }
  150. public reset() {
  151. this._alphaBlend = false;
  152. this._blendFunctionParameters[0] = null;
  153. this._blendFunctionParameters[1] = null;
  154. this._blendFunctionParameters[2] = null;
  155. this._blendFunctionParameters[3] = null;
  156. this._isAlphaBlendDirty = true;
  157. this._isBlendFunctionParametersDirty = false;
  158. }
  159. public apply(gl: WebGLRenderingContext) {
  160. if (!this.isDirty) {
  161. return;
  162. }
  163. // Alpha blend
  164. if (this._isAlphaBlendDirty) {
  165. if (this._alphaBlend === true) {
  166. gl.enable(gl.BLEND);
  167. } else if (this._alphaBlend === false) {
  168. gl.disable(gl.BLEND);
  169. }
  170. this._isAlphaBlendDirty = false;
  171. }
  172. // Alpha function
  173. if (this._isBlendFunctionParametersDirty) {
  174. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  175. this._isBlendFunctionParametersDirty = false;
  176. }
  177. }
  178. }
  179. var compileShader = (gl: WebGLRenderingContext, source: string, type: string, defines: string): WebGLShader => {
  180. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  181. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  182. gl.compileShader(shader);
  183. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  184. throw new Error(gl.getShaderInfoLog(shader));
  185. }
  186. return shader;
  187. };
  188. var getSamplingParameters = (samplingMode: number, generateMipMaps: boolean, gl: WebGLRenderingContext): { min: number; mag: number } => {
  189. var magFilter = gl.NEAREST;
  190. var minFilter = gl.NEAREST;
  191. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  192. magFilter = gl.LINEAR;
  193. if (generateMipMaps) {
  194. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  195. } else {
  196. minFilter = gl.LINEAR;
  197. }
  198. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  199. magFilter = gl.LINEAR;
  200. if (generateMipMaps) {
  201. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  202. } else {
  203. minFilter = gl.LINEAR;
  204. }
  205. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  206. magFilter = gl.NEAREST;
  207. if (generateMipMaps) {
  208. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  209. } else {
  210. minFilter = gl.NEAREST;
  211. }
  212. }
  213. return {
  214. min: minFilter,
  215. mag: magFilter
  216. }
  217. }
  218. var prepareWebGLTexture = (texture: WebGLTexture, gl: WebGLRenderingContext, scene: Scene, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  219. processFunction: (width: number, height: number) => void, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE) => {
  220. var engine = scene.getEngine();
  221. var potWidth = Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  222. var potHeight = Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  223. gl.bindTexture(gl.TEXTURE_2D, texture);
  224. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  225. processFunction(potWidth, potHeight);
  226. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  227. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  228. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  229. if (!noMipmap && !isCompressed) {
  230. gl.generateMipmap(gl.TEXTURE_2D);
  231. }
  232. gl.bindTexture(gl.TEXTURE_2D, null);
  233. engine._activeTexturesCache = [];
  234. texture._baseWidth = width;
  235. texture._baseHeight = height;
  236. texture._width = potWidth;
  237. texture._height = potHeight;
  238. texture.isReady = true;
  239. scene._removePendingData(texture);
  240. };
  241. var partialLoad = (url: string, index: number, loadedImages: any, scene,
  242. onfinish: (images: HTMLImageElement[]) => void) => {
  243. var img: HTMLImageElement;
  244. var onload = () => {
  245. loadedImages[index] = img;
  246. loadedImages._internalCount++;
  247. scene._removePendingData(img);
  248. if (loadedImages._internalCount == 6) {
  249. onfinish(loadedImages);
  250. }
  251. };
  252. var onerror = () => {
  253. scene._removePendingData(img);
  254. };
  255. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  256. scene._addPendingData(img);
  257. }
  258. var cascadeLoad = (rootUrl: string, scene,
  259. onfinish: (images: HTMLImageElement[]) => void, extensions: string[]) => {
  260. var loadedImages:any = [];
  261. loadedImages._internalCount = 0;
  262. for (var index = 0; index < 6; index++) {
  263. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  264. }
  265. };
  266. export class EngineCapabilities {
  267. public maxTexturesImageUnits: number;
  268. public maxTextureSize: number;
  269. public maxCubemapTextureSize: number;
  270. public maxRenderTextureSize: number;
  271. public standardDerivatives: boolean;
  272. public s3tc;
  273. public textureFloat: boolean;
  274. public textureAnisotropicFilterExtension;
  275. public maxAnisotropy: number;
  276. public instancedArrays;
  277. public uintIndices: boolean;
  278. }
  279. export class Engine {
  280. // Const statics
  281. private static _ALPHA_DISABLE = 0;
  282. private static _ALPHA_ADD = 1;
  283. private static _ALPHA_COMBINE = 2;
  284. private static _DELAYLOADSTATE_NONE = 0;
  285. private static _DELAYLOADSTATE_LOADED = 1;
  286. private static _DELAYLOADSTATE_LOADING = 2;
  287. private static _DELAYLOADSTATE_NOTLOADED = 4;
  288. public static get ALPHA_DISABLE(): number {
  289. return Engine._ALPHA_DISABLE;
  290. }
  291. public static get ALPHA_ADD(): number {
  292. return Engine._ALPHA_ADD;
  293. }
  294. public static get ALPHA_COMBINE(): number {
  295. return Engine._ALPHA_COMBINE;
  296. }
  297. public static get DELAYLOADSTATE_NONE(): number {
  298. return Engine._DELAYLOADSTATE_NONE;
  299. }
  300. public static get DELAYLOADSTATE_LOADED(): number {
  301. return Engine._DELAYLOADSTATE_LOADED;
  302. }
  303. public static get DELAYLOADSTATE_LOADING(): number {
  304. return Engine._DELAYLOADSTATE_LOADING;
  305. }
  306. public static get DELAYLOADSTATE_NOTLOADED(): number {
  307. return Engine._DELAYLOADSTATE_NOTLOADED;
  308. }
  309. public static get Version(): string {
  310. return "2.0.0";
  311. }
  312. // Updatable statics so stick with vars here
  313. public static Epsilon = 0.001;
  314. public static CollisionsEpsilon = 0.001;
  315. public static ShadersRepository = "Babylon/Shaders/";
  316. // Public members
  317. public isFullscreen = false;
  318. public isPointerLock = false;
  319. public cullBackFaces = true;
  320. public renderEvenInBackground = true;
  321. public scenes = new Array<Scene>();
  322. // Private Members
  323. private _gl: WebGLRenderingContext;
  324. private _renderingCanvas: HTMLCanvasElement;
  325. private _windowIsBackground = false;
  326. private _audioEngine: BABYLON.AudioEngine;
  327. private _onBlur: () => void;
  328. private _onFocus: () => void;
  329. private _onFullscreenChange: () => void;
  330. private _onPointerLockChange: () => void;
  331. private _hardwareScalingLevel: number;
  332. private _caps: EngineCapabilities;
  333. private _pointerLockRequested: boolean;
  334. private _alphaTest: boolean;
  335. private _runningLoop = false;
  336. private _renderFunction: () => void;
  337. private _resizeLoadingUI: () => void;
  338. private _loadingDiv: HTMLDivElement;
  339. private _loadingTextDiv: HTMLDivElement;
  340. private _loadingDivBackgroundColor = "black";
  341. private _drawCalls = 0;
  342. // States
  343. private _depthCullingState = new _DepthCullingState();
  344. private _alphaState = new _AlphaState();
  345. private _alphaMode = Engine.ALPHA_DISABLE;
  346. // Cache
  347. private _loadedTexturesCache = new Array<WebGLTexture>();
  348. public _activeTexturesCache = new Array<BaseTexture>();
  349. private _currentEffect: Effect;
  350. private _compiledEffects = {};
  351. private _vertexAttribArrays: boolean[];
  352. private _cachedViewport: Viewport;
  353. private _cachedVertexBuffers: any;
  354. private _cachedIndexBuffer: WebGLBuffer;
  355. private _cachedEffectForVertexBuffers: Effect;
  356. private _currentRenderTarget: WebGLTexture;
  357. private _canvasClientRect: ClientRect;
  358. private _uintIndicesCurrentlySet = false;
  359. private _workingCanvas: HTMLCanvasElement;
  360. private _workingContext: CanvasRenderingContext2D;
  361. constructor(canvas: HTMLCanvasElement, antialias?: boolean, options?) {
  362. this._renderingCanvas = canvas;
  363. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  364. options = options || {};
  365. options.antialias = antialias;
  366. // GL
  367. try {
  368. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  369. } catch (e) {
  370. throw new Error("WebGL not supported");
  371. }
  372. if (!this._gl) {
  373. throw new Error("WebGL not supported");
  374. }
  375. this._onBlur = () => {
  376. this._windowIsBackground = true;
  377. };
  378. this._onFocus = () => {
  379. this._windowIsBackground = false;
  380. };
  381. window.addEventListener("blur", this._onBlur);
  382. window.addEventListener("focus", this._onFocus);
  383. // Textures
  384. this._workingCanvas = document.createElement("canvas");
  385. this._workingContext = this._workingCanvas.getContext("2d");
  386. // Viewport
  387. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  388. this.resize();
  389. // Caps
  390. this._caps = new EngineCapabilities();
  391. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  392. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  393. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  394. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  395. // Extensions
  396. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  397. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  398. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  399. 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');
  400. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  401. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  402. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  403. // Depth buffer
  404. this.setDepthBuffer(true);
  405. this.setDepthFunctionToLessOrEqual();
  406. this.setDepthWrite(true);
  407. // Fullscreen
  408. this._onFullscreenChange = () => {
  409. if (document.fullscreen !== undefined) {
  410. this.isFullscreen = document.fullscreen;
  411. } else if (document.mozFullScreen !== undefined) {
  412. this.isFullscreen = document.mozFullScreen;
  413. } else if (document.webkitIsFullScreen !== undefined) {
  414. this.isFullscreen = document.webkitIsFullScreen;
  415. } else if (document.msIsFullScreen !== undefined) {
  416. this.isFullscreen = document.msIsFullScreen;
  417. }
  418. // Pointer lock
  419. if (this.isFullscreen && this._pointerLockRequested) {
  420. canvas.requestPointerLock = canvas.requestPointerLock ||
  421. canvas.msRequestPointerLock ||
  422. canvas.mozRequestPointerLock ||
  423. canvas.webkitRequestPointerLock;
  424. if (canvas.requestPointerLock) {
  425. canvas.requestPointerLock();
  426. }
  427. }
  428. };
  429. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  430. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  431. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  432. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  433. // Pointer lock
  434. this._onPointerLockChange = () => {
  435. this.isPointerLock = (document.mozPointerLockElement === canvas ||
  436. document.webkitPointerLockElement === canvas ||
  437. document.msPointerLockElement === canvas ||
  438. document.pointerLockElement === canvas
  439. );
  440. };
  441. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  442. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  443. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  444. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  445. this._audioEngine = new BABYLON.AudioEngine();
  446. Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  447. }
  448. public getAudioEngine(): AudioEngine {
  449. return this._audioEngine;
  450. }
  451. public getAspectRatio(camera: Camera): number {
  452. var viewport = camera.viewport;
  453. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  454. }
  455. public getRenderWidth(): number {
  456. if (this._currentRenderTarget) {
  457. return this._currentRenderTarget._width;
  458. }
  459. return this._renderingCanvas.width;
  460. }
  461. public getRenderHeight(): number {
  462. if (this._currentRenderTarget) {
  463. return this._currentRenderTarget._height;
  464. }
  465. return this._renderingCanvas.height;
  466. }
  467. public getRenderingCanvas(): HTMLCanvasElement {
  468. return this._renderingCanvas;
  469. }
  470. public getRenderingCanvasClientRect(): ClientRect {
  471. return this._renderingCanvas.getBoundingClientRect();
  472. }
  473. public setHardwareScalingLevel(level: number): void {
  474. this._hardwareScalingLevel = level;
  475. this.resize();
  476. }
  477. public getHardwareScalingLevel(): number {
  478. return this._hardwareScalingLevel;
  479. }
  480. public getLoadedTexturesCache(): WebGLTexture[] {
  481. return this._loadedTexturesCache;
  482. }
  483. public getCaps(): EngineCapabilities {
  484. return this._caps;
  485. }
  486. public get drawCalls(): number {
  487. return this._drawCalls;
  488. }
  489. // Methods
  490. public resetDrawCalls(): void {
  491. this._drawCalls = 0;
  492. }
  493. public setDepthFunctionToGreater(): void {
  494. this._depthCullingState.depthFunc = this._gl.GREATER;
  495. }
  496. public setDepthFunctionToGreaterOrEqual(): void {
  497. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  498. }
  499. public setDepthFunctionToLess(): void {
  500. this._depthCullingState.depthFunc = this._gl.LESS;
  501. }
  502. public setDepthFunctionToLessOrEqual(): void {
  503. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  504. }
  505. public stopRenderLoop(): void {
  506. this._renderFunction = null;
  507. this._runningLoop = false;
  508. }
  509. public _renderLoop(): void {
  510. var shouldRender = true;
  511. if (!this.renderEvenInBackground && this._windowIsBackground) {
  512. shouldRender = false;
  513. }
  514. if (shouldRender) {
  515. // Start new frame
  516. this.beginFrame();
  517. if (this._renderFunction) {
  518. this._renderFunction();
  519. }
  520. // Present
  521. this.endFrame();
  522. }
  523. if (this._runningLoop) {
  524. // Register new frame
  525. BABYLON.Tools.QueueNewFrame(() => {
  526. this._renderLoop();
  527. });
  528. }
  529. }
  530. public runRenderLoop(renderFunction: () => void): void {
  531. this._runningLoop = true;
  532. this._renderFunction = renderFunction;
  533. BABYLON.Tools.QueueNewFrame(() => {
  534. this._renderLoop();
  535. });
  536. }
  537. public switchFullscreen(requestPointerLock: boolean): void {
  538. if (this.isFullscreen) {
  539. BABYLON.Tools.ExitFullscreen();
  540. } else {
  541. this._pointerLockRequested = requestPointerLock;
  542. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  543. }
  544. }
  545. public clear(color: any, backBuffer: boolean, depthStencil: boolean): void {
  546. this.applyStates();
  547. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  548. if (this._depthCullingState.depthMask) {
  549. this._gl.clearDepth(1.0);
  550. }
  551. var mode = 0;
  552. if (backBuffer)
  553. mode |= this._gl.COLOR_BUFFER_BIT;
  554. if (depthStencil && this._depthCullingState.depthMask)
  555. mode |= this._gl.DEPTH_BUFFER_BIT;
  556. this._gl.clear(mode);
  557. }
  558. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  559. var width = requiredWidth || this._renderingCanvas.width;
  560. var height = requiredHeight || this._renderingCanvas.height;
  561. var x = viewport.x || 0;
  562. var y = viewport.y || 0;
  563. this._cachedViewport = viewport;
  564. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  565. }
  566. public setDirectViewport(x: number, y: number, width: number, height: number): void {
  567. this._cachedViewport = null;
  568. this._gl.viewport(x, y, width, height);
  569. }
  570. public beginFrame(): void {
  571. BABYLON.Tools._MeasureFps();
  572. }
  573. public endFrame(): void {
  574. this.flushFramebuffer();
  575. }
  576. public resize(): void {
  577. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  578. }
  579. public setSize(width: number, height: number): void {
  580. this._renderingCanvas.width = width;
  581. this._renderingCanvas.height = height;
  582. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  583. }
  584. public bindFramebuffer(texture: WebGLTexture): void {
  585. this._currentRenderTarget = texture;
  586. var gl = this._gl;
  587. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  588. this._gl.viewport(0, 0, texture._width, texture._height);
  589. this.wipeCaches();
  590. }
  591. public unBindFramebuffer(texture: WebGLTexture): void {
  592. this._currentRenderTarget = null;
  593. if (texture.generateMipMaps) {
  594. var gl = this._gl;
  595. gl.bindTexture(gl.TEXTURE_2D, texture);
  596. gl.generateMipmap(gl.TEXTURE_2D);
  597. gl.bindTexture(gl.TEXTURE_2D, null);
  598. }
  599. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  600. }
  601. public flushFramebuffer(): void {
  602. // this._gl.flush();
  603. }
  604. public restoreDefaultFramebuffer(): void {
  605. this._currentRenderTarget = null;
  606. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  607. this.setViewport(this._cachedViewport);
  608. this.wipeCaches();
  609. }
  610. // VBOs
  611. private _resetVertexBufferBinding(): void {
  612. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  613. this._cachedVertexBuffers = null;
  614. }
  615. public createVertexBuffer(vertices: number[]): WebGLBuffer {
  616. var vbo = this._gl.createBuffer();
  617. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  618. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  619. this._resetVertexBufferBinding();
  620. vbo.references = 1;
  621. return vbo;
  622. }
  623. public createDynamicVertexBuffer(capacity: number): WebGLBuffer {
  624. var vbo = this._gl.createBuffer();
  625. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  626. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  627. this._resetVertexBufferBinding();
  628. vbo.references = 1;
  629. return vbo;
  630. }
  631. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: any, offset?: number): void {
  632. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  633. if (offset === undefined) {
  634. offset = 0;
  635. }
  636. if (vertices instanceof Float32Array) {
  637. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  638. } else {
  639. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  640. }
  641. this._resetVertexBufferBinding();
  642. }
  643. private _resetIndexBufferBinding(): void {
  644. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  645. this._cachedIndexBuffer = null;
  646. }
  647. public createIndexBuffer(indices: number[]): WebGLBuffer {
  648. var vbo = this._gl.createBuffer();
  649. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  650. // Check for 32 bits indices
  651. var arrayBuffer;
  652. var need32Bits = false;
  653. if (this._caps.uintIndices) {
  654. for (var index = 0; index < indices.length; index++) {
  655. if (indices[index] > 65535) {
  656. need32Bits = true;
  657. break;
  658. }
  659. }
  660. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  661. } else {
  662. arrayBuffer = new Uint16Array(indices);
  663. }
  664. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  665. this._resetIndexBufferBinding();
  666. vbo.references = 1;
  667. vbo.is32Bits = need32Bits;
  668. return vbo;
  669. }
  670. public bindBuffers(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  671. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  672. this._cachedVertexBuffers = vertexBuffer;
  673. this._cachedEffectForVertexBuffers = effect;
  674. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  675. var offset = 0;
  676. for (var index = 0; index < vertexDeclaration.length; index++) {
  677. var order = effect.getAttributeLocation(index);
  678. if (order >= 0) {
  679. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  680. }
  681. offset += vertexDeclaration[index] * 4;
  682. }
  683. }
  684. if (this._cachedIndexBuffer !== indexBuffer) {
  685. this._cachedIndexBuffer = indexBuffer;
  686. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  687. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  688. }
  689. }
  690. public bindMultiBuffers(vertexBuffers: VertexBuffer[], indexBuffer: WebGLBuffer, effect: Effect): void {
  691. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  692. this._cachedVertexBuffers = vertexBuffers;
  693. this._cachedEffectForVertexBuffers = effect;
  694. var attributes = effect.getAttributesNames();
  695. for (var index = 0; index < attributes.length; index++) {
  696. var order = effect.getAttributeLocation(index);
  697. if (order >= 0) {
  698. var vertexBuffer = vertexBuffers[attributes[index]];
  699. if (!vertexBuffer) {
  700. continue;
  701. }
  702. var stride = vertexBuffer.getStrideSize();
  703. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  704. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  705. }
  706. }
  707. }
  708. if (indexBuffer!= null && this._cachedIndexBuffer !== indexBuffer) {
  709. this._cachedIndexBuffer = indexBuffer;
  710. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  711. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  712. }
  713. }
  714. public _releaseBuffer(buffer: WebGLBuffer): boolean {
  715. buffer.references--;
  716. if (buffer.references === 0) {
  717. this._gl.deleteBuffer(buffer);
  718. return true;
  719. }
  720. return false;
  721. }
  722. public createInstancesBuffer(capacity: number): WebGLBuffer {
  723. var buffer = this._gl.createBuffer();
  724. buffer.capacity = capacity;
  725. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  726. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  727. return buffer;
  728. }
  729. public deleteInstancesBuffer(buffer: WebGLBuffer): void {
  730. this._gl.deleteBuffer(buffer);
  731. }
  732. public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[]): void {
  733. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  734. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  735. for (var index = 0; index < 4; index++) {
  736. var offsetLocation = offsetLocations[index];
  737. this._gl.enableVertexAttribArray(offsetLocation);
  738. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  739. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  740. }
  741. }
  742. public unBindInstancesBuffer(instancesBuffer: WebGLBuffer, offsetLocations: number[]): void {
  743. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  744. for (var index = 0; index < 4; index++) {
  745. var offsetLocation = offsetLocations[index];
  746. this._gl.disableVertexAttribArray(offsetLocation);
  747. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  748. }
  749. }
  750. public applyStates() {
  751. this._depthCullingState.apply(this._gl);
  752. this._alphaState.apply(this._gl);
  753. }
  754. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  755. // Apply states
  756. this.applyStates();
  757. // Render
  758. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  759. if (instancesCount) {
  760. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  761. return;
  762. }
  763. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  764. this._drawCalls++;
  765. }
  766. public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
  767. // Apply states
  768. this.applyStates();
  769. if (instancesCount) {
  770. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  771. return;
  772. }
  773. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  774. this._drawCalls++;
  775. }
  776. // Shaders
  777. public _releaseEffect(effect: Effect): void {
  778. if (this._compiledEffects[effect._key]) {
  779. delete this._compiledEffects[effect._key];
  780. if (effect.getProgram()) {
  781. this._gl.deleteProgram(effect.getProgram());
  782. }
  783. }
  784. }
  785. public createEffect(baseName: any, attributesNames: string[], uniformsNames: string[], samplers: string[], defines: string, fallbacks?: EffectFallbacks,
  786. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  787. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  788. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  789. var name = vertex + "+" + fragment + "@" + defines;
  790. if (this._compiledEffects[name]) {
  791. return this._compiledEffects[name];
  792. }
  793. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  794. effect._key = name;
  795. this._compiledEffects[name] = effect;
  796. return effect;
  797. }
  798. public createEffectForParticles(fragmentName: string, uniformsNames: string[]= [], samplers: string[]= [], defines = "", fallbacks?: EffectFallbacks,
  799. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  800. return this.createEffect(
  801. {
  802. vertex: "particles",
  803. fragmentElement: fragmentName
  804. },
  805. ["position", "color", "options"],
  806. ["view", "projection"].concat(uniformsNames),
  807. ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  808. }
  809. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: string): WebGLProgram {
  810. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  811. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  812. var shaderProgram = this._gl.createProgram();
  813. this._gl.attachShader(shaderProgram, vertexShader);
  814. this._gl.attachShader(shaderProgram, fragmentShader);
  815. this._gl.linkProgram(shaderProgram);
  816. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  817. if (!linked) {
  818. var error = this._gl.getProgramInfoLog(shaderProgram);
  819. if (error) {
  820. throw new Error(error);
  821. }
  822. }
  823. this._gl.deleteShader(vertexShader);
  824. this._gl.deleteShader(fragmentShader);
  825. return shaderProgram;
  826. }
  827. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): WebGLUniformLocation[] {
  828. var results = [];
  829. for (var index = 0; index < uniformsNames.length; index++) {
  830. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  831. }
  832. return results;
  833. }
  834. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  835. var results = [];
  836. for (var index = 0; index < attributesNames.length; index++) {
  837. try {
  838. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  839. } catch (e) {
  840. results.push(-1);
  841. }
  842. }
  843. return results;
  844. }
  845. public enableEffect(effect: Effect): void {
  846. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  847. if (effect && effect.onBind) {
  848. effect.onBind(effect);
  849. }
  850. return;
  851. }
  852. this._vertexAttribArrays = this._vertexAttribArrays || [];
  853. // Use program
  854. this._gl.useProgram(effect.getProgram());
  855. for (var i in this._vertexAttribArrays) {
  856. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  857. continue;
  858. }
  859. this._vertexAttribArrays[i] = false;
  860. this._gl.disableVertexAttribArray(i);
  861. }
  862. var attributesCount = effect.getAttributesCount();
  863. for (var index = 0; index < attributesCount; index++) {
  864. // Attributes
  865. var order = effect.getAttributeLocation(index);
  866. if (order >= 0) {
  867. this._vertexAttribArrays[order] = true;
  868. this._gl.enableVertexAttribArray(order);
  869. }
  870. }
  871. this._currentEffect = effect;
  872. if (effect.onBind) {
  873. effect.onBind(effect);
  874. }
  875. }
  876. public setArray(uniform: WebGLUniformLocation, array: number[]): void {
  877. if (!uniform)
  878. return;
  879. this._gl.uniform1fv(uniform, array);
  880. }
  881. public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void {
  882. if (!uniform)
  883. return;
  884. this._gl.uniformMatrix4fv(uniform, false, matrices);
  885. }
  886. public setMatrix(uniform: WebGLUniformLocation, matrix: Matrix): void {
  887. if (!uniform)
  888. return;
  889. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  890. }
  891. public setFloat(uniform: WebGLUniformLocation, value: number): void {
  892. if (!uniform)
  893. return;
  894. this._gl.uniform1f(uniform, value);
  895. }
  896. public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void {
  897. if (!uniform)
  898. return;
  899. this._gl.uniform2f(uniform, x, y);
  900. }
  901. public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void {
  902. if (!uniform)
  903. return;
  904. this._gl.uniform3f(uniform, x, y, z);
  905. }
  906. public setBool(uniform: WebGLUniformLocation, bool: number): void {
  907. if (!uniform)
  908. return;
  909. this._gl.uniform1i(uniform, bool);
  910. }
  911. public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void {
  912. if (!uniform)
  913. return;
  914. this._gl.uniform4f(uniform, x, y, z, w);
  915. }
  916. public setColor3(uniform: WebGLUniformLocation, color3: Color3): void {
  917. if (!uniform)
  918. return;
  919. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  920. }
  921. public setColor4(uniform: WebGLUniformLocation, color3: Color3, alpha: number): void {
  922. if (!uniform)
  923. return;
  924. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  925. }
  926. // States
  927. public setState(culling: boolean, force?: boolean): void {
  928. // Culling
  929. if (this._depthCullingState.cull !== culling || force) {
  930. if (culling) {
  931. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  932. this._depthCullingState.cull = true;
  933. } else {
  934. this._depthCullingState.cull = false;
  935. }
  936. }
  937. }
  938. public setDepthBuffer(enable: boolean): void {
  939. this._depthCullingState.depthTest = enable;
  940. }
  941. public getDepthWrite(): boolean {
  942. return this._depthCullingState.depthMask;
  943. }
  944. public setDepthWrite(enable: boolean): void {
  945. this._depthCullingState.depthMask = enable;
  946. }
  947. public setColorWrite(enable: boolean): void {
  948. this._gl.colorMask(enable, enable, enable, enable);
  949. }
  950. public setAlphaMode(mode: number): void {
  951. switch (mode) {
  952. case BABYLON.Engine.ALPHA_DISABLE:
  953. this.setDepthWrite(true);
  954. this._alphaState.alphaBlend = false;
  955. break;
  956. case BABYLON.Engine.ALPHA_COMBINE:
  957. this.setDepthWrite(false);
  958. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  959. this._alphaState.alphaBlend = true;
  960. break;
  961. case BABYLON.Engine.ALPHA_ADD:
  962. this.setDepthWrite(false);
  963. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  964. this._alphaState.alphaBlend = true;
  965. break;
  966. }
  967. this._alphaMode = mode;
  968. }
  969. public getAlphaMode(): number {
  970. return this._alphaMode;
  971. }
  972. public setAlphaTesting(enable: boolean): void {
  973. this._alphaTest = enable;
  974. }
  975. public getAlphaTesting(): boolean {
  976. return this._alphaTest;
  977. }
  978. // Textures
  979. public wipeCaches(): void {
  980. this._activeTexturesCache = [];
  981. this._currentEffect = null;
  982. this._depthCullingState.reset();
  983. this._alphaState.reset();
  984. this._cachedVertexBuffers = null;
  985. this._cachedIndexBuffer = null;
  986. this._cachedEffectForVertexBuffers = null;
  987. }
  988. public setSamplingMode(texture: WebGLTexture, samplingMode: number): void {
  989. var gl = this._gl;
  990. gl.bindTexture(gl.TEXTURE_2D, texture);
  991. var magFilter = gl.NEAREST;
  992. var minFilter = gl.NEAREST;
  993. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  994. magFilter = gl.LINEAR;
  995. minFilter = gl.LINEAR;
  996. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  997. magFilter = gl.LINEAR;
  998. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  999. }
  1000. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  1001. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  1002. gl.bindTexture(gl.TEXTURE_2D, null);
  1003. }
  1004. 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 {
  1005. var texture = this._gl.createTexture();
  1006. var extension: string;
  1007. var fromData: any = false;
  1008. if (url.substr(0, 5) === "data:") {
  1009. fromData = true;
  1010. }
  1011. if (!fromData)
  1012. extension = url.substr(url.length - 4, 4).toLowerCase();
  1013. else {
  1014. var oldUrl = url;
  1015. fromData = oldUrl.split(':');
  1016. url = oldUrl;
  1017. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  1018. }
  1019. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  1020. var isTGA = (extension === ".tga");
  1021. scene._addPendingData(texture);
  1022. texture.url = url;
  1023. texture.noMipmap = noMipmap;
  1024. texture.references = 1;
  1025. this._loadedTexturesCache.push(texture);
  1026. var onerror = () => {
  1027. scene._removePendingData(texture);
  1028. if (onError) {
  1029. onError();
  1030. }
  1031. };
  1032. if (isTGA) {
  1033. var callback = (arrayBuffer) => {
  1034. var data = new Uint8Array(arrayBuffer);
  1035. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  1036. prepareWebGLTexture(texture, this._gl, scene, header.width, header.height, invertY, noMipmap, false, () => {
  1037. Internals.TGATools.UploadContent(this._gl, data);
  1038. if (onLoad) {
  1039. onLoad();
  1040. }
  1041. }, samplingMode);
  1042. };
  1043. if (!(fromData instanceof Array))
  1044. BABYLON.Tools.LoadFile(url, arrayBuffer => {
  1045. callback(arrayBuffer);
  1046. }, onerror, scene.database, true);
  1047. else
  1048. callback(buffer);
  1049. } else if (isDDS) {
  1050. callback = (data) => {
  1051. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  1052. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  1053. prepareWebGLTexture(texture, this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, () => {
  1054. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, info, loadMipmap, 1);
  1055. if (onLoad) {
  1056. onLoad();
  1057. }
  1058. }, samplingMode);
  1059. };
  1060. if (!(fromData instanceof Array))
  1061. BABYLON.Tools.LoadFile(url, data => {
  1062. callback(data);
  1063. }, onerror, scene.database, true);
  1064. else
  1065. callback(buffer);
  1066. } else {
  1067. var onload = (img) => {
  1068. prepareWebGLTexture(texture, this._gl, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight) => {
  1069. var isPot = (img.width == potWidth && img.height == potHeight);
  1070. if (!isPot) {
  1071. this._workingCanvas.width = potWidth;
  1072. this._workingCanvas.height = potHeight;
  1073. this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  1074. }
  1075. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, isPot ? img : this._workingCanvas);
  1076. if (onLoad) {
  1077. onLoad();
  1078. }
  1079. }, samplingMode);
  1080. };
  1081. if (!(fromData instanceof Array))
  1082. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  1083. else
  1084. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  1085. }
  1086. return texture;
  1087. }
  1088. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number): WebGLTexture {
  1089. var texture = this._gl.createTexture();
  1090. width = Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  1091. height = Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  1092. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1093. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  1094. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1095. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1096. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1097. this._activeTexturesCache = [];
  1098. texture._baseWidth = width;
  1099. texture._baseHeight = height;
  1100. texture._width = width;
  1101. texture._height = height;
  1102. texture.isReady = false;
  1103. texture.generateMipMaps = generateMipMaps;
  1104. texture.references = 1;
  1105. this._loadedTexturesCache.push(texture);
  1106. return texture;
  1107. }
  1108. public updateDynamicTexture(texture: WebGLTexture, canvas: HTMLCanvasElement, invertY: boolean): void {
  1109. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1110. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  1111. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  1112. if (texture.generateMipMaps) {
  1113. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1114. }
  1115. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1116. this._activeTexturesCache = [];
  1117. texture.isReady = true;
  1118. }
  1119. public updateVideoTexture(texture: WebGLTexture, video: HTMLVideoElement, invertY: boolean): void {
  1120. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1121. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  1122. // Scale the video if it is a NPOT using the current working canvas
  1123. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  1124. if (!texture._workingCanvas) {
  1125. texture._workingCanvas = document.createElement("canvas");
  1126. texture._workingContext = texture._workingCanvas.getContext("2d");
  1127. texture._workingCanvas.width = texture._width;
  1128. texture._workingCanvas.height = texture._height;
  1129. }
  1130. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  1131. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  1132. } else {
  1133. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  1134. }
  1135. if (texture.generateMipMaps) {
  1136. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1137. }
  1138. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1139. this._activeTexturesCache = [];
  1140. texture.isReady = true;
  1141. }
  1142. public createRenderTargetTexture(size: any, options): WebGLTexture {
  1143. // old version had a "generateMipMaps" arg instead of options.
  1144. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  1145. // in the same way, generateDepthBuffer is defaulted to true
  1146. var generateMipMaps = false;
  1147. var generateDepthBuffer = true;
  1148. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1149. if (options !== undefined) {
  1150. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  1151. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  1152. if (options.samplingMode !== undefined) {
  1153. samplingMode = options.samplingMode;
  1154. }
  1155. }
  1156. var gl = this._gl;
  1157. var texture = gl.createTexture();
  1158. gl.bindTexture(gl.TEXTURE_2D, texture);
  1159. var width = size.width || size;
  1160. var height = size.height || size;
  1161. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  1162. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  1163. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  1164. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1165. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1166. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  1167. var depthBuffer: WebGLRenderbuffer;
  1168. // Create the depth buffer
  1169. if (generateDepthBuffer) {
  1170. depthBuffer = gl.createRenderbuffer();
  1171. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  1172. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  1173. }
  1174. // Create the framebuffer
  1175. var framebuffer = gl.createFramebuffer();
  1176. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  1177. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  1178. if (generateDepthBuffer) {
  1179. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  1180. }
  1181. // Unbind
  1182. gl.bindTexture(gl.TEXTURE_2D, null);
  1183. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  1184. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  1185. texture._framebuffer = framebuffer;
  1186. if (generateDepthBuffer) {
  1187. texture._depthBuffer = depthBuffer;
  1188. }
  1189. texture._width = width;
  1190. texture._height = height;
  1191. texture.isReady = true;
  1192. texture.generateMipMaps = generateMipMaps;
  1193. texture.references = 1;
  1194. this._activeTexturesCache = [];
  1195. this._loadedTexturesCache.push(texture);
  1196. return texture;
  1197. }
  1198. public createCubeTexture(rootUrl: string, scene: Scene, extensions: string[], noMipmap?: boolean): WebGLTexture {
  1199. var gl = this._gl;
  1200. var texture = gl.createTexture();
  1201. texture.isCube = true;
  1202. texture.url = rootUrl;
  1203. texture.references = 1;
  1204. this._loadedTexturesCache.push(texture);
  1205. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  1206. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  1207. if (isDDS) {
  1208. BABYLON.Tools.LoadFile(rootUrl, data => {
  1209. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  1210. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  1211. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1212. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  1213. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, info, loadMipmap, 6);
  1214. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  1215. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1216. }
  1217. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1218. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  1219. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1220. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1221. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1222. this._activeTexturesCache = [];
  1223. texture._width = info.width;
  1224. texture._height = info.height;
  1225. texture.isReady = true;
  1226. }, null, null, true);
  1227. } else {
  1228. cascadeLoad(rootUrl, scene, imgs => {
  1229. var width = Tools.GetExponantOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize);
  1230. var height = width;
  1231. this._workingCanvas.width = width;
  1232. this._workingCanvas.height = height;
  1233. var faces = [
  1234. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  1235. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  1236. ];
  1237. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1238. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  1239. for (var index = 0; index < faces.length; index++) {
  1240. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  1241. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._workingCanvas);
  1242. }
  1243. if (!noMipmap) {
  1244. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1245. }
  1246. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1247. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  1248. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1249. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1250. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1251. this._activeTexturesCache = [];
  1252. texture._width = width;
  1253. texture._height = height;
  1254. texture.isReady = true;
  1255. }, extensions);
  1256. }
  1257. return texture;
  1258. }
  1259. public _releaseTexture(texture: WebGLTexture): void {
  1260. var gl = this._gl;
  1261. if (texture._framebuffer) {
  1262. gl.deleteFramebuffer(texture._framebuffer);
  1263. }
  1264. if (texture._depthBuffer) {
  1265. gl.deleteRenderbuffer(texture._depthBuffer);
  1266. }
  1267. gl.deleteTexture(texture);
  1268. // Unbind channels
  1269. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  1270. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1271. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1272. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1273. this._activeTexturesCache[channel] = null;
  1274. }
  1275. var index = this._loadedTexturesCache.indexOf(texture);
  1276. if (index !== -1) {
  1277. this._loadedTexturesCache.splice(index, 1);
  1278. }
  1279. }
  1280. public bindSamplers(effect: Effect): void {
  1281. this._gl.useProgram(effect.getProgram());
  1282. var samplers = effect.getSamplers();
  1283. for (var index = 0; index < samplers.length; index++) {
  1284. var uniform = effect.getUniform(samplers[index]);
  1285. this._gl.uniform1i(uniform, index);
  1286. }
  1287. this._currentEffect = null;
  1288. }
  1289. public _bindTexture(channel: number, texture: WebGLTexture): void {
  1290. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1291. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1292. this._activeTexturesCache[channel] = null;
  1293. }
  1294. public setTextureFromPostProcess(channel: number, postProcess: PostProcess): void {
  1295. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  1296. }
  1297. public setTexture(channel: number, texture: BaseTexture): void {
  1298. if (channel < 0) {
  1299. return;
  1300. }
  1301. // Not ready?
  1302. if (!texture || !texture.isReady()) {
  1303. if (this._activeTexturesCache[channel] != null) {
  1304. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1305. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1306. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1307. this._activeTexturesCache[channel] = null;
  1308. }
  1309. return;
  1310. }
  1311. // Video
  1312. if (texture instanceof BABYLON.VideoTexture) {
  1313. if ((<VideoTexture>texture).update()) {
  1314. this._activeTexturesCache[channel] = null;
  1315. }
  1316. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  1317. texture.delayLoad();
  1318. return;
  1319. }
  1320. if (this._activeTexturesCache[channel] == texture) {
  1321. return;
  1322. }
  1323. this._activeTexturesCache[channel] = texture;
  1324. var internalTexture = texture.getInternalTexture();
  1325. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1326. if (internalTexture.isCube) {
  1327. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  1328. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  1329. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  1330. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  1331. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  1332. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  1333. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  1334. }
  1335. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  1336. } else {
  1337. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  1338. if (internalTexture._cachedWrapU !== texture.wrapU) {
  1339. internalTexture._cachedWrapU = texture.wrapU;
  1340. switch (texture.wrapU) {
  1341. case BABYLON.Texture.WRAP_ADDRESSMODE:
  1342. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  1343. break;
  1344. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  1345. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  1346. break;
  1347. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  1348. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  1349. break;
  1350. }
  1351. }
  1352. if (internalTexture._cachedWrapV !== texture.wrapV) {
  1353. internalTexture._cachedWrapV = texture.wrapV;
  1354. switch (texture.wrapV) {
  1355. case BABYLON.Texture.WRAP_ADDRESSMODE:
  1356. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  1357. break;
  1358. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  1359. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  1360. break;
  1361. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  1362. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  1363. break;
  1364. }
  1365. }
  1366. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  1367. }
  1368. }
  1369. public _setAnisotropicLevel(key: number, texture: BaseTexture) {
  1370. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  1371. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  1372. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  1373. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  1374. }
  1375. }
  1376. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  1377. var data = new Uint8Array(height * width * 4);
  1378. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  1379. return data;
  1380. }
  1381. // Dispose
  1382. public dispose(): void {
  1383. this.hideLoadingUI();
  1384. this.stopRenderLoop();
  1385. // Release scenes
  1386. while (this.scenes.length) {
  1387. this.scenes[0].dispose();
  1388. }
  1389. // Release effects
  1390. for (var name in this._compiledEffects) {
  1391. this._gl.deleteProgram(this._compiledEffects[name]._program);
  1392. }
  1393. // Unbind
  1394. for (var i in this._vertexAttribArrays) {
  1395. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  1396. continue;
  1397. }
  1398. this._gl.disableVertexAttribArray(i);
  1399. }
  1400. // Events
  1401. window.removeEventListener("blur", this._onBlur);
  1402. window.removeEventListener("focus", this._onFocus);
  1403. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  1404. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  1405. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  1406. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  1407. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  1408. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  1409. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  1410. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  1411. }
  1412. // Loading screen
  1413. public displayLoadingUI(): void {
  1414. this._loadingDiv = document.createElement("div");
  1415. this._loadingDiv.style.opacity = "0";
  1416. this._loadingDiv.style.transition = "opacity 1.5s ease";
  1417. // Loading text
  1418. this._loadingTextDiv = document.createElement("div");
  1419. this._loadingTextDiv.style.position = "absolute";
  1420. this._loadingTextDiv.style.left = "0";
  1421. this._loadingTextDiv.style.top = "50%";
  1422. this._loadingTextDiv.style.marginTop = "80px";
  1423. this._loadingTextDiv.style.width = "100%";
  1424. this._loadingTextDiv.style.height = "20px";
  1425. this._loadingTextDiv.style.fontFamily = "Arial";
  1426. this._loadingTextDiv.style.fontSize = "14px";
  1427. this._loadingTextDiv.style.color = "white";
  1428. this._loadingTextDiv.style.textAlign = "center";
  1429. this._loadingTextDiv.innerHTML = "Loading";
  1430. this._loadingDiv.appendChild(this._loadingTextDiv);
  1431. // Loading img
  1432. var imgBack = new Image();
  1433. 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==";
  1434. imgBack.style.position = "absolute";
  1435. imgBack.style.left = "50%";
  1436. imgBack.style.top = "50%";
  1437. imgBack.style.marginLeft = "-50px";
  1438. imgBack.style.marginTop = "-50px";
  1439. imgBack.style.transition = "transform 1.0s ease";
  1440. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  1441. var deg = 360;
  1442. var onTransitionEnd = () => {
  1443. deg += 360;
  1444. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  1445. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  1446. }
  1447. imgBack.addEventListener("transitionend", onTransitionEnd);
  1448. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  1449. this._loadingDiv.appendChild(imgBack);
  1450. // front image
  1451. var imgFront = new Image();
  1452. 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=";
  1453. imgFront.style.position = "absolute";
  1454. imgFront.style.left = "50%";
  1455. imgFront.style.top = "50%";
  1456. imgFront.style.marginLeft = "-50px";
  1457. imgFront.style.marginTop = "-50px";
  1458. this._loadingDiv.appendChild(imgFront);
  1459. // Resize
  1460. this._resizeLoadingUI = () => {
  1461. var canvasRect = this.getRenderingCanvasClientRect();
  1462. this._loadingDiv.style.position = "absolute";
  1463. this._loadingDiv.style.left = canvasRect.left + "px";
  1464. this._loadingDiv.style.top = canvasRect.top + "px";
  1465. this._loadingDiv.style.width = canvasRect.width + "px";
  1466. this._loadingDiv.style.height = canvasRect.height + "px";
  1467. }
  1468. this._resizeLoadingUI();
  1469. window.addEventListener("resize", this._resizeLoadingUI);
  1470. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  1471. document.body.appendChild(this._loadingDiv);
  1472. setTimeout(() => {
  1473. this._loadingDiv.style.opacity = "1";
  1474. imgBack.style.transform = "rotateZ(360deg)";
  1475. imgBack.style.webkitTransform = "rotateZ(360deg)";
  1476. }, 0);
  1477. }
  1478. public set loadingUIText(text: string) {
  1479. if (!this._loadingDiv) {
  1480. return;
  1481. }
  1482. this._loadingTextDiv.innerHTML = text;
  1483. }
  1484. public get loadingUIBackgroundColor(): string {
  1485. return this._loadingDivBackgroundColor;
  1486. }
  1487. public set loadingUIBackgroundColor(color: string) {
  1488. this._loadingDivBackgroundColor = color;
  1489. if (!this._loadingDiv) {
  1490. return;
  1491. }
  1492. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  1493. }
  1494. public hideLoadingUI(): void {
  1495. if (!this._loadingDiv) {
  1496. return;
  1497. }
  1498. var onTransitionEnd = () => {
  1499. if (!this._loadingDiv) {
  1500. return;
  1501. }
  1502. document.body.removeChild(this._loadingDiv);
  1503. window.removeEventListener("resize", this._resizeLoadingUI);
  1504. this._loadingDiv = null;
  1505. }
  1506. this._loadingDiv.style.opacity = "0";
  1507. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  1508. }
  1509. // Statics
  1510. public static isSupported(): boolean {
  1511. try {
  1512. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  1513. if (navigator.isCocoonJS) {
  1514. return true;
  1515. }
  1516. var tempcanvas = document.createElement("canvas");
  1517. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  1518. return gl != null && !!window.WebGLRenderingContext;
  1519. } catch (e) {
  1520. return false;
  1521. }
  1522. }
  1523. }
  1524. }