babylon.engine.js 119 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var compileShader = function (gl, source, type, defines) {
  4. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  6. gl.compileShader(shader);
  7. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  8. throw new Error(gl.getShaderInfoLog(shader));
  9. }
  10. return shader;
  11. };
  12. var HALF_FLOAT_OES = 0x8D61;
  13. var getWebGLTextureType = function (gl, type) {
  14. if (type === Engine.TEXTURETYPE_FLOAT) {
  15. return gl.FLOAT;
  16. }
  17. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  18. // Add Half Float Constant.
  19. return HALF_FLOAT_OES;
  20. }
  21. return gl.UNSIGNED_BYTE;
  22. };
  23. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  24. var magFilter = gl.NEAREST;
  25. var minFilter = gl.NEAREST;
  26. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  27. magFilter = gl.LINEAR;
  28. if (generateMipMaps) {
  29. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  30. }
  31. else {
  32. minFilter = gl.LINEAR;
  33. }
  34. }
  35. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  36. magFilter = gl.LINEAR;
  37. if (generateMipMaps) {
  38. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  39. }
  40. else {
  41. minFilter = gl.LINEAR;
  42. }
  43. }
  44. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  45. magFilter = gl.NEAREST;
  46. if (generateMipMaps) {
  47. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  48. }
  49. else {
  50. minFilter = gl.NEAREST;
  51. }
  52. }
  53. return {
  54. min: minFilter,
  55. mag: magFilter
  56. };
  57. };
  58. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  59. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60. var engine = scene.getEngine();
  61. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  62. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  63. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  64. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  65. texture._baseWidth = width;
  66. texture._baseHeight = height;
  67. texture._width = potWidth;
  68. texture._height = potHeight;
  69. texture.isReady = true;
  70. processFunction(potWidth, potHeight);
  71. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  72. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  73. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  74. if (!noMipmap && !isCompressed) {
  75. gl.generateMipmap(gl.TEXTURE_2D);
  76. }
  77. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  78. engine.resetTextureCache();
  79. scene._removePendingData(texture);
  80. if (onLoad) {
  81. onLoad();
  82. }
  83. };
  84. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  85. var img;
  86. var onload = function () {
  87. loadedImages[index] = img;
  88. loadedImages._internalCount++;
  89. scene._removePendingData(img);
  90. if (loadedImages._internalCount === 6) {
  91. onfinish(loadedImages);
  92. }
  93. };
  94. var onerror = function () {
  95. scene._removePendingData(img);
  96. };
  97. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  98. scene._addPendingData(img);
  99. };
  100. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  101. var loadedImages = [];
  102. loadedImages._internalCount = 0;
  103. for (var index = 0; index < 6; index++) {
  104. partialLoad(files[index], index, loadedImages, scene, onfinish);
  105. }
  106. };
  107. var InstancingAttributeInfo = (function () {
  108. function InstancingAttributeInfo() {
  109. }
  110. return InstancingAttributeInfo;
  111. })();
  112. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  113. var EngineCapabilities = (function () {
  114. function EngineCapabilities() {
  115. }
  116. return EngineCapabilities;
  117. })();
  118. BABYLON.EngineCapabilities = EngineCapabilities;
  119. /**
  120. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  121. */
  122. var Engine = (function () {
  123. /**
  124. * @constructor
  125. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  126. * @param {boolean} [antialias] - enable antialias
  127. * @param options - further options to be sent to the getContext function
  128. */
  129. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  130. var _this = this;
  131. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  132. // Public members
  133. this.isFullscreen = false;
  134. this.isPointerLock = false;
  135. this.cullBackFaces = true;
  136. this.renderEvenInBackground = true;
  137. // To enable/disable IDB support and avoid XHR on .manifest
  138. this.enableOfflineSupport = true;
  139. this.scenes = new Array();
  140. this._windowIsBackground = false;
  141. this._webGLVersion = "1.0";
  142. this._drawCalls = new BABYLON.PerfCounter();
  143. this._renderingQueueLaunched = false;
  144. this._activeRenderLoops = [];
  145. // FPS
  146. this.fpsRange = 60;
  147. this.previousFramesDuration = [];
  148. this.fps = 60;
  149. this.deltaTime = 0;
  150. // States
  151. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  152. this._stencilState = new BABYLON.Internals._StencilState();
  153. this._alphaState = new BABYLON.Internals._AlphaState();
  154. this._alphaMode = Engine.ALPHA_DISABLE;
  155. // Cache
  156. this._loadedTexturesCache = new Array();
  157. this._maxTextureChannels = 16;
  158. this._activeTexturesCache = new Array(this._maxTextureChannels);
  159. this._compiledEffects = {};
  160. this._uintIndicesCurrentlySet = false;
  161. this._currentBoundBuffer = new Array();
  162. this._currentBufferPointers = [];
  163. this._currentInstanceLocations = new Array();
  164. this._currentInstanceBuffers = new Array();
  165. this._renderingCanvas = canvas;
  166. this._externalData = new BABYLON.StringDictionary();
  167. options = options || {};
  168. if (antialias != null) {
  169. options.antialias = antialias;
  170. }
  171. if (options.preserveDrawingBuffer === undefined) {
  172. options.preserveDrawingBuffer = false;
  173. }
  174. // Checks if some of the format renders first to allow the use of webgl inspector.
  175. var renderToFullFloat = this._canRenderToFloatTexture();
  176. var renderToHalfFloat = this._canRenderToHalfFloatTexture();
  177. // GL
  178. //try {
  179. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  180. // if (this._gl) {
  181. // this._webGLVersion = "2.0";
  182. // }
  183. //} catch (e) {
  184. // // Do nothing
  185. //}
  186. if (!this._gl) {
  187. try {
  188. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  189. }
  190. catch (e) {
  191. throw new Error("WebGL not supported");
  192. }
  193. }
  194. if (!this._gl) {
  195. throw new Error("WebGL not supported");
  196. }
  197. this._onBlur = function () {
  198. _this._windowIsBackground = true;
  199. };
  200. this._onFocus = function () {
  201. _this._windowIsBackground = false;
  202. };
  203. window.addEventListener("blur", this._onBlur);
  204. window.addEventListener("focus", this._onFocus);
  205. // Viewport
  206. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  207. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  208. this.resize();
  209. // Caps
  210. this._isStencilEnable = options.stencil;
  211. this._caps = new EngineCapabilities();
  212. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  213. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  214. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  215. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  216. // Infos
  217. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  218. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  219. if (rendererInfo != null) {
  220. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  221. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  222. }
  223. if (!this._glVendor) {
  224. this._glVendor = "Unknown vendor";
  225. }
  226. if (!this._glRenderer) {
  227. this._glRenderer = "Unknown renderer";
  228. }
  229. // Extensions
  230. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  231. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  232. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  233. 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');
  234. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  235. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  236. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  237. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  238. this._caps.highPrecisionShaderSupported = true;
  239. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  240. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  241. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  242. this._caps.textureFloatRender = renderToFullFloat;
  243. this._caps.textureHalfFloat = (this._gl.getExtension('OES_texture_half_float') !== null);
  244. this._caps.textureHalfFloatLinearFiltering = this._gl.getExtension('OES_texture_half_float_linear');
  245. this._caps.textureHalfFloatRender = renderToHalfFloat;
  246. if (this._gl.getShaderPrecisionFormat) {
  247. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  248. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  249. }
  250. // Depth buffer
  251. this.setDepthBuffer(true);
  252. this.setDepthFunctionToLessOrEqual();
  253. this.setDepthWrite(true);
  254. // Fullscreen
  255. this._onFullscreenChange = function () {
  256. if (document.fullscreen !== undefined) {
  257. _this.isFullscreen = document.fullscreen;
  258. }
  259. else if (document.mozFullScreen !== undefined) {
  260. _this.isFullscreen = document.mozFullScreen;
  261. }
  262. else if (document.webkitIsFullScreen !== undefined) {
  263. _this.isFullscreen = document.webkitIsFullScreen;
  264. }
  265. else if (document.msIsFullScreen !== undefined) {
  266. _this.isFullscreen = document.msIsFullScreen;
  267. }
  268. // Pointer lock
  269. if (_this.isFullscreen && _this._pointerLockRequested) {
  270. canvas.requestPointerLock = canvas.requestPointerLock ||
  271. canvas.msRequestPointerLock ||
  272. canvas.mozRequestPointerLock ||
  273. canvas.webkitRequestPointerLock;
  274. if (canvas.requestPointerLock) {
  275. canvas.requestPointerLock();
  276. }
  277. }
  278. };
  279. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  280. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  281. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  282. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  283. // Pointer lock
  284. this._onPointerLockChange = function () {
  285. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  286. document.webkitPointerLockElement === canvas ||
  287. document.msPointerLockElement === canvas ||
  288. document.pointerLockElement === canvas);
  289. };
  290. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  291. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  292. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  293. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  294. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  295. Engine.audioEngine = new BABYLON.AudioEngine();
  296. }
  297. //default loading screen
  298. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  299. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  300. }
  301. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  302. get: function () {
  303. return Engine._ALPHA_DISABLE;
  304. },
  305. enumerable: true,
  306. configurable: true
  307. });
  308. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  309. get: function () {
  310. return Engine._ALPHA_ONEONE;
  311. },
  312. enumerable: true,
  313. configurable: true
  314. });
  315. Object.defineProperty(Engine, "ALPHA_ADD", {
  316. get: function () {
  317. return Engine._ALPHA_ADD;
  318. },
  319. enumerable: true,
  320. configurable: true
  321. });
  322. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  323. get: function () {
  324. return Engine._ALPHA_COMBINE;
  325. },
  326. enumerable: true,
  327. configurable: true
  328. });
  329. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  330. get: function () {
  331. return Engine._ALPHA_SUBTRACT;
  332. },
  333. enumerable: true,
  334. configurable: true
  335. });
  336. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  337. get: function () {
  338. return Engine._ALPHA_MULTIPLY;
  339. },
  340. enumerable: true,
  341. configurable: true
  342. });
  343. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  344. get: function () {
  345. return Engine._ALPHA_MAXIMIZED;
  346. },
  347. enumerable: true,
  348. configurable: true
  349. });
  350. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  351. get: function () {
  352. return Engine._DELAYLOADSTATE_NONE;
  353. },
  354. enumerable: true,
  355. configurable: true
  356. });
  357. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  358. get: function () {
  359. return Engine._DELAYLOADSTATE_LOADED;
  360. },
  361. enumerable: true,
  362. configurable: true
  363. });
  364. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  365. get: function () {
  366. return Engine._DELAYLOADSTATE_LOADING;
  367. },
  368. enumerable: true,
  369. configurable: true
  370. });
  371. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  372. get: function () {
  373. return Engine._DELAYLOADSTATE_NOTLOADED;
  374. },
  375. enumerable: true,
  376. configurable: true
  377. });
  378. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  379. get: function () {
  380. return Engine._TEXTUREFORMAT_ALPHA;
  381. },
  382. enumerable: true,
  383. configurable: true
  384. });
  385. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  386. get: function () {
  387. return Engine._TEXTUREFORMAT_LUMINANCE;
  388. },
  389. enumerable: true,
  390. configurable: true
  391. });
  392. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  393. get: function () {
  394. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  395. },
  396. enumerable: true,
  397. configurable: true
  398. });
  399. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  400. get: function () {
  401. return Engine._TEXTUREFORMAT_RGB;
  402. },
  403. enumerable: true,
  404. configurable: true
  405. });
  406. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  407. get: function () {
  408. return Engine._TEXTUREFORMAT_RGBA;
  409. },
  410. enumerable: true,
  411. configurable: true
  412. });
  413. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  414. get: function () {
  415. return Engine._TEXTURETYPE_UNSIGNED_INT;
  416. },
  417. enumerable: true,
  418. configurable: true
  419. });
  420. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  421. get: function () {
  422. return Engine._TEXTURETYPE_FLOAT;
  423. },
  424. enumerable: true,
  425. configurable: true
  426. });
  427. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  428. get: function () {
  429. return Engine._TEXTURETYPE_HALF_FLOAT;
  430. },
  431. enumerable: true,
  432. configurable: true
  433. });
  434. Object.defineProperty(Engine, "Version", {
  435. get: function () {
  436. return "2.5-alpha";
  437. },
  438. enumerable: true,
  439. configurable: true
  440. });
  441. Object.defineProperty(Engine.prototype, "webGLVersion", {
  442. get: function () {
  443. return this._webGLVersion;
  444. },
  445. enumerable: true,
  446. configurable: true
  447. });
  448. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  449. /**
  450. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  451. */
  452. get: function () {
  453. return this._isStencilEnable;
  454. },
  455. enumerable: true,
  456. configurable: true
  457. });
  458. Engine.prototype._prepareWorkingCanvas = function () {
  459. if (this._workingCanvas) {
  460. return;
  461. }
  462. this._workingCanvas = document.createElement("canvas");
  463. this._workingContext = this._workingCanvas.getContext("2d");
  464. };
  465. Engine.prototype.resetTextureCache = function () {
  466. for (var index = 0; index < this._maxTextureChannels; index++) {
  467. this._activeTexturesCache[index] = null;
  468. }
  469. };
  470. Engine.prototype.getGlInfo = function () {
  471. return {
  472. vendor: this._glVendor,
  473. renderer: this._glRenderer,
  474. version: this._glVersion
  475. };
  476. };
  477. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  478. if (useScreen === void 0) { useScreen = false; }
  479. var viewport = camera.viewport;
  480. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  481. };
  482. Engine.prototype.getRenderWidth = function (useScreen) {
  483. if (useScreen === void 0) { useScreen = false; }
  484. if (!useScreen && this._currentRenderTarget) {
  485. return this._currentRenderTarget._width;
  486. }
  487. return this._renderingCanvas.width;
  488. };
  489. Engine.prototype.getRenderHeight = function (useScreen) {
  490. if (useScreen === void 0) { useScreen = false; }
  491. if (!useScreen && this._currentRenderTarget) {
  492. return this._currentRenderTarget._height;
  493. }
  494. return this._renderingCanvas.height;
  495. };
  496. Engine.prototype.getRenderingCanvas = function () {
  497. return this._renderingCanvas;
  498. };
  499. Engine.prototype.getRenderingCanvasClientRect = function () {
  500. return this._renderingCanvas.getBoundingClientRect();
  501. };
  502. Engine.prototype.setHardwareScalingLevel = function (level) {
  503. this._hardwareScalingLevel = level;
  504. this.resize();
  505. };
  506. Engine.prototype.getHardwareScalingLevel = function () {
  507. return this._hardwareScalingLevel;
  508. };
  509. Engine.prototype.getLoadedTexturesCache = function () {
  510. return this._loadedTexturesCache;
  511. };
  512. Engine.prototype.getCaps = function () {
  513. return this._caps;
  514. };
  515. Object.defineProperty(Engine.prototype, "drawCalls", {
  516. get: function () {
  517. return this._drawCalls.current;
  518. },
  519. enumerable: true,
  520. configurable: true
  521. });
  522. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  523. get: function () {
  524. return this._drawCalls;
  525. },
  526. enumerable: true,
  527. configurable: true
  528. });
  529. Engine.prototype.getDepthFunction = function () {
  530. return this._depthCullingState.depthFunc;
  531. };
  532. Engine.prototype.setDepthFunction = function (depthFunc) {
  533. this._depthCullingState.depthFunc = depthFunc;
  534. };
  535. Engine.prototype.setDepthFunctionToGreater = function () {
  536. this._depthCullingState.depthFunc = this._gl.GREATER;
  537. };
  538. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  539. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  540. };
  541. Engine.prototype.setDepthFunctionToLess = function () {
  542. this._depthCullingState.depthFunc = this._gl.LESS;
  543. };
  544. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  545. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  546. };
  547. Engine.prototype.getStencilBuffer = function () {
  548. return this._stencilState.stencilTest;
  549. };
  550. Engine.prototype.setStencilBuffer = function (enable) {
  551. this._stencilState.stencilTest = enable;
  552. };
  553. Engine.prototype.getStencilMask = function () {
  554. return this._stencilState.stencilMask;
  555. };
  556. Engine.prototype.setStencilMask = function (mask) {
  557. this._stencilState.stencilMask = mask;
  558. };
  559. Engine.prototype.getStencilFunction = function () {
  560. return this._stencilState.stencilFunc;
  561. };
  562. Engine.prototype.getStencilFunctionReference = function () {
  563. return this._stencilState.stencilFuncRef;
  564. };
  565. Engine.prototype.getStencilFunctionMask = function () {
  566. return this._stencilState.stencilFuncMask;
  567. };
  568. Engine.prototype.setStencilFunction = function (stencilFunc) {
  569. this._stencilState.stencilFunc = stencilFunc;
  570. };
  571. Engine.prototype.setStencilFunctionReference = function (reference) {
  572. this._stencilState.stencilFuncRef = reference;
  573. };
  574. Engine.prototype.setStencilFunctionMask = function (mask) {
  575. this._stencilState.stencilFuncMask = mask;
  576. };
  577. Engine.prototype.getStencilOperationFail = function () {
  578. return this._stencilState.stencilOpStencilFail;
  579. };
  580. Engine.prototype.getStencilOperationDepthFail = function () {
  581. return this._stencilState.stencilOpDepthFail;
  582. };
  583. Engine.prototype.getStencilOperationPass = function () {
  584. return this._stencilState.stencilOpStencilDepthPass;
  585. };
  586. Engine.prototype.setStencilOperationFail = function (operation) {
  587. this._stencilState.stencilOpStencilFail = operation;
  588. };
  589. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  590. this._stencilState.stencilOpDepthFail = operation;
  591. };
  592. Engine.prototype.setStencilOperationPass = function (operation) {
  593. this._stencilState.stencilOpStencilDepthPass = operation;
  594. };
  595. /**
  596. * stop executing a render loop function and remove it from the execution array
  597. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  598. */
  599. Engine.prototype.stopRenderLoop = function (renderFunction) {
  600. if (!renderFunction) {
  601. this._activeRenderLoops = [];
  602. return;
  603. }
  604. var index = this._activeRenderLoops.indexOf(renderFunction);
  605. if (index >= 0) {
  606. this._activeRenderLoops.splice(index, 1);
  607. }
  608. };
  609. Engine.prototype._renderLoop = function () {
  610. var shouldRender = true;
  611. if (!this.renderEvenInBackground && this._windowIsBackground) {
  612. shouldRender = false;
  613. }
  614. if (shouldRender) {
  615. // Start new frame
  616. this.beginFrame();
  617. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  618. var renderFunction = this._activeRenderLoops[index];
  619. renderFunction();
  620. }
  621. // Present
  622. this.endFrame();
  623. }
  624. if (this._activeRenderLoops.length > 0) {
  625. // Register new frame
  626. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  627. }
  628. else {
  629. this._renderingQueueLaunched = false;
  630. }
  631. };
  632. /**
  633. * Register and execute a render loop. The engine can have more than one render function.
  634. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  635. * @example
  636. * engine.runRenderLoop(function () {
  637. * scene.render()
  638. * })
  639. */
  640. Engine.prototype.runRenderLoop = function (renderFunction) {
  641. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  642. return;
  643. }
  644. this._activeRenderLoops.push(renderFunction);
  645. if (!this._renderingQueueLaunched) {
  646. this._renderingQueueLaunched = true;
  647. this._bindedRenderFunction = this._renderLoop.bind(this);
  648. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  649. }
  650. };
  651. /**
  652. * Toggle full screen mode.
  653. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  654. * @param {any} options - an options object to be sent to the requestFullscreen function
  655. */
  656. Engine.prototype.switchFullscreen = function (requestPointerLock, options) {
  657. if (this.isFullscreen) {
  658. BABYLON.Tools.ExitFullscreen();
  659. }
  660. else {
  661. this._pointerLockRequested = requestPointerLock;
  662. BABYLON.Tools.RequestFullscreen(this._renderingCanvas, options);
  663. }
  664. };
  665. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  666. if (stencil === void 0) { stencil = false; }
  667. this.applyStates();
  668. var mode = 0;
  669. if (backBuffer) {
  670. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  671. mode |= this._gl.COLOR_BUFFER_BIT;
  672. }
  673. if (depth) {
  674. this._gl.clearDepth(1.0);
  675. mode |= this._gl.DEPTH_BUFFER_BIT;
  676. }
  677. if (stencil) {
  678. this._gl.clearStencil(0);
  679. mode |= this._gl.STENCIL_BUFFER_BIT;
  680. }
  681. this._gl.clear(mode);
  682. };
  683. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  684. var gl = this._gl;
  685. // Save state
  686. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  687. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  688. // Change state
  689. gl.enable(gl.SCISSOR_TEST);
  690. gl.scissor(x, y, width, height);
  691. // Clear
  692. this.clear(clearColor, true, true, true);
  693. // Restore state
  694. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  695. if (curScissor === true) {
  696. gl.enable(gl.SCISSOR_TEST);
  697. }
  698. else {
  699. gl.disable(gl.SCISSOR_TEST);
  700. }
  701. };
  702. /**
  703. * Set the WebGL's viewport
  704. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  705. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  706. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  707. */
  708. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  709. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  710. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  711. var x = viewport.x || 0;
  712. var y = viewport.y || 0;
  713. this._cachedViewport = viewport;
  714. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  715. };
  716. /**
  717. * Directly set the WebGL Viewport
  718. * The x, y, width & height are directly passed to the WebGL call
  719. * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state.
  720. */
  721. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  722. var currentViewport = this._cachedViewport;
  723. this._cachedViewport = null;
  724. this._gl.viewport(x, y, width, height);
  725. return currentViewport;
  726. };
  727. Engine.prototype.beginFrame = function () {
  728. this._measureFps();
  729. };
  730. Engine.prototype.endFrame = function () {
  731. //this.flushFramebuffer();
  732. };
  733. /**
  734. * resize the view according to the canvas' size.
  735. * @example
  736. * window.addEventListener("resize", function () {
  737. * engine.resize();
  738. * });
  739. */
  740. Engine.prototype.resize = function () {
  741. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  742. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  743. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  744. for (var index = 0; index < this.scenes.length; index++) {
  745. var scene = this.scenes[index];
  746. if (BABYLON.DebugLayer && scene.debugLayer.isVisible()) {
  747. scene.debugLayer._syncPositions();
  748. }
  749. }
  750. };
  751. /**
  752. * force a specific size of the canvas
  753. * @param {number} width - the new canvas' width
  754. * @param {number} height - the new canvas' height
  755. */
  756. Engine.prototype.setSize = function (width, height) {
  757. this._renderingCanvas.width = width;
  758. this._renderingCanvas.height = height;
  759. for (var index = 0; index < this.scenes.length; index++) {
  760. var scene = this.scenes[index];
  761. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  762. var cam = scene.cameras[camIndex];
  763. cam._currentRenderId = 0;
  764. }
  765. }
  766. };
  767. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  768. this._currentRenderTarget = texture;
  769. this.bindUnboundFramebuffer(texture._framebuffer);
  770. var gl = this._gl;
  771. if (texture.isCube) {
  772. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  773. }
  774. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  775. this.wipeCaches();
  776. };
  777. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  778. if (this._currentFramebuffer !== framebuffer) {
  779. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  780. this._currentFramebuffer = framebuffer;
  781. }
  782. };
  783. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  784. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  785. this._currentRenderTarget = null;
  786. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  787. var gl = this._gl;
  788. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  789. gl.generateMipmap(gl.TEXTURE_2D);
  790. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  791. }
  792. this.bindUnboundFramebuffer(null);
  793. };
  794. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  795. if (texture.generateMipMaps) {
  796. var gl = this._gl;
  797. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  798. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  799. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  800. }
  801. };
  802. Engine.prototype.flushFramebuffer = function () {
  803. this._gl.flush();
  804. };
  805. Engine.prototype.restoreDefaultFramebuffer = function () {
  806. this._currentRenderTarget = null;
  807. this.bindUnboundFramebuffer(null);
  808. this.setViewport(this._cachedViewport);
  809. this.wipeCaches();
  810. };
  811. // VBOs
  812. Engine.prototype._resetVertexBufferBinding = function () {
  813. this.bindArrayBuffer(null);
  814. this._cachedVertexBuffers = null;
  815. };
  816. Engine.prototype.createVertexBuffer = function (vertices) {
  817. var vbo = this._gl.createBuffer();
  818. this.bindArrayBuffer(vbo);
  819. if (vertices instanceof Float32Array) {
  820. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  821. }
  822. else {
  823. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  824. }
  825. this._resetVertexBufferBinding();
  826. vbo.references = 1;
  827. return vbo;
  828. };
  829. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  830. var vbo = this._gl.createBuffer();
  831. this.bindArrayBuffer(vbo);
  832. if (vertices instanceof Float32Array) {
  833. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  834. }
  835. else {
  836. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  837. }
  838. this._resetVertexBufferBinding();
  839. vbo.references = 1;
  840. return vbo;
  841. };
  842. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  843. this.bindArrayBuffer(vertexBuffer);
  844. if (offset === undefined) {
  845. offset = 0;
  846. }
  847. if (count === undefined) {
  848. if (vertices instanceof Float32Array) {
  849. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  850. }
  851. else {
  852. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  853. }
  854. }
  855. else {
  856. if (vertices instanceof Float32Array) {
  857. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  858. }
  859. else {
  860. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  861. }
  862. }
  863. this._resetVertexBufferBinding();
  864. };
  865. Engine.prototype._resetIndexBufferBinding = function () {
  866. this.bindIndexBuffer(null);
  867. this._cachedIndexBuffer = null;
  868. };
  869. Engine.prototype.createIndexBuffer = function (indices) {
  870. var vbo = this._gl.createBuffer();
  871. this.bindIndexBuffer(vbo);
  872. // Check for 32 bits indices
  873. var arrayBuffer;
  874. var need32Bits = false;
  875. if (this._caps.uintIndices) {
  876. for (var index = 0; index < indices.length; index++) {
  877. if (indices[index] > 65535) {
  878. need32Bits = true;
  879. break;
  880. }
  881. }
  882. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  883. }
  884. else {
  885. arrayBuffer = new Uint16Array(indices);
  886. }
  887. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  888. this._resetIndexBufferBinding();
  889. vbo.references = 1;
  890. vbo.is32Bits = need32Bits;
  891. return vbo;
  892. };
  893. Engine.prototype.bindArrayBuffer = function (buffer) {
  894. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  895. };
  896. Engine.prototype.bindIndexBuffer = function (buffer) {
  897. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  898. };
  899. Engine.prototype.bindBuffer = function (buffer, target) {
  900. if (this._currentBoundBuffer[target] !== buffer) {
  901. this._gl.bindBuffer(target, buffer);
  902. this._currentBoundBuffer[target] = buffer;
  903. }
  904. };
  905. Engine.prototype.updateArrayBuffer = function (data) {
  906. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  907. };
  908. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  909. var pointer = this._currentBufferPointers[indx];
  910. var changed = false;
  911. if (!pointer) {
  912. changed = true;
  913. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  914. }
  915. else {
  916. if (pointer.buffer !== buffer) {
  917. pointer.buffer = buffer;
  918. changed = true;
  919. }
  920. if (pointer.size !== size) {
  921. pointer.size = size;
  922. changed = true;
  923. }
  924. if (pointer.type !== type) {
  925. pointer.type = type;
  926. changed = true;
  927. }
  928. if (pointer.normalized !== normalized) {
  929. pointer.normalized = normalized;
  930. changed = true;
  931. }
  932. if (pointer.stride !== stride) {
  933. pointer.stride = stride;
  934. changed = true;
  935. }
  936. if (pointer.offset !== offset) {
  937. pointer.offset = offset;
  938. changed = true;
  939. }
  940. }
  941. if (changed) {
  942. this.bindArrayBuffer(buffer);
  943. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  944. }
  945. };
  946. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  947. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  948. this._cachedVertexBuffers = vertexBuffer;
  949. this._cachedEffectForVertexBuffers = effect;
  950. var offset = 0;
  951. for (var index = 0; index < vertexDeclaration.length; index++) {
  952. var order = effect.getAttributeLocation(index);
  953. if (order >= 0) {
  954. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  955. }
  956. offset += vertexDeclaration[index] * 4;
  957. }
  958. }
  959. if (this._cachedIndexBuffer !== indexBuffer) {
  960. this._cachedIndexBuffer = indexBuffer;
  961. this.bindIndexBuffer(indexBuffer);
  962. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  963. }
  964. };
  965. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  966. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  967. this._cachedVertexBuffers = vertexBuffers;
  968. this._cachedEffectForVertexBuffers = effect;
  969. var attributes = effect.getAttributesNames();
  970. for (var index = 0; index < attributes.length; index++) {
  971. var order = effect.getAttributeLocation(index);
  972. if (order >= 0) {
  973. var vertexBuffer = vertexBuffers[attributes[index]];
  974. if (!vertexBuffer) {
  975. continue;
  976. }
  977. var buffer = vertexBuffer.getBuffer();
  978. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  979. if (vertexBuffer.getIsInstanced()) {
  980. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  981. this._currentInstanceLocations.push(order);
  982. this._currentInstanceBuffers.push(buffer);
  983. }
  984. }
  985. }
  986. }
  987. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  988. this._cachedIndexBuffer = indexBuffer;
  989. this.bindIndexBuffer(indexBuffer);
  990. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  991. }
  992. };
  993. Engine.prototype.unbindInstanceAttributes = function () {
  994. var boundBuffer;
  995. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  996. var instancesBuffer = this._currentInstanceBuffers[i];
  997. if (boundBuffer != instancesBuffer) {
  998. boundBuffer = instancesBuffer;
  999. this.bindArrayBuffer(instancesBuffer);
  1000. }
  1001. var offsetLocation = this._currentInstanceLocations[i];
  1002. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  1003. }
  1004. this._currentInstanceBuffers.length = 0;
  1005. this._currentInstanceLocations.length = 0;
  1006. };
  1007. Engine.prototype._releaseBuffer = function (buffer) {
  1008. buffer.references--;
  1009. if (buffer.references === 0) {
  1010. this._gl.deleteBuffer(buffer);
  1011. return true;
  1012. }
  1013. return false;
  1014. };
  1015. Engine.prototype.createInstancesBuffer = function (capacity) {
  1016. var buffer = this._gl.createBuffer();
  1017. buffer.capacity = capacity;
  1018. this.bindArrayBuffer(buffer);
  1019. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  1020. return buffer;
  1021. };
  1022. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  1023. this._gl.deleteBuffer(buffer);
  1024. };
  1025. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  1026. this.bindArrayBuffer(instancesBuffer);
  1027. if (data) {
  1028. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  1029. }
  1030. if (offsetLocations[0].index !== undefined) {
  1031. var stride = 0;
  1032. for (var i = 0; i < offsetLocations.length; i++) {
  1033. var ai = offsetLocations[i];
  1034. stride += ai.attributeSize * 4;
  1035. }
  1036. for (var i = 0; i < offsetLocations.length; i++) {
  1037. var ai = offsetLocations[i];
  1038. this._gl.enableVertexAttribArray(ai.index);
  1039. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  1040. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  1041. this._currentInstanceLocations.push(ai.index);
  1042. this._currentInstanceBuffers.push(instancesBuffer);
  1043. }
  1044. }
  1045. else {
  1046. for (var index = 0; index < 4; index++) {
  1047. var offsetLocation = offsetLocations[index];
  1048. this._gl.enableVertexAttribArray(offsetLocation);
  1049. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  1050. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  1051. this._currentInstanceLocations.push(offsetLocation);
  1052. this._currentInstanceBuffers.push(instancesBuffer);
  1053. }
  1054. }
  1055. };
  1056. Engine.prototype.applyStates = function () {
  1057. this._depthCullingState.apply(this._gl);
  1058. this._stencilState.apply(this._gl);
  1059. this._alphaState.apply(this._gl);
  1060. };
  1061. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  1062. // Apply states
  1063. this.applyStates();
  1064. this._drawCalls.addCount(1, false);
  1065. // Render
  1066. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  1067. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  1068. if (instancesCount) {
  1069. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  1070. return;
  1071. }
  1072. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  1073. };
  1074. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  1075. // Apply states
  1076. this.applyStates();
  1077. this._drawCalls.addCount(1, false);
  1078. if (instancesCount) {
  1079. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  1080. return;
  1081. }
  1082. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  1083. };
  1084. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  1085. // Apply states
  1086. this.applyStates();
  1087. this._drawCalls.addCount(1, false);
  1088. if (instancesCount) {
  1089. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  1090. return;
  1091. }
  1092. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  1093. };
  1094. // Shaders
  1095. Engine.prototype._releaseEffect = function (effect) {
  1096. if (this._compiledEffects[effect._key]) {
  1097. delete this._compiledEffects[effect._key];
  1098. if (effect.getProgram()) {
  1099. this._gl.deleteProgram(effect.getProgram());
  1100. }
  1101. }
  1102. };
  1103. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  1104. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  1105. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  1106. var name = vertex + "+" + fragment + "@" + defines;
  1107. if (this._compiledEffects[name]) {
  1108. return this._compiledEffects[name];
  1109. }
  1110. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  1111. effect._key = name;
  1112. this._compiledEffects[name] = effect;
  1113. return effect;
  1114. };
  1115. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  1116. if (uniformsNames === void 0) { uniformsNames = []; }
  1117. if (samplers === void 0) { samplers = []; }
  1118. if (defines === void 0) { defines = ""; }
  1119. return this.createEffect({
  1120. vertex: "particles",
  1121. fragmentElement: fragmentName
  1122. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  1123. };
  1124. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  1125. context = context || this._gl;
  1126. var vertexShader = compileShader(context, vertexCode, "vertex", defines);
  1127. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines);
  1128. var shaderProgram = context.createProgram();
  1129. context.attachShader(shaderProgram, vertexShader);
  1130. context.attachShader(shaderProgram, fragmentShader);
  1131. context.linkProgram(shaderProgram);
  1132. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  1133. if (!linked) {
  1134. var error = context.getProgramInfoLog(shaderProgram);
  1135. if (error) {
  1136. throw new Error(error);
  1137. }
  1138. }
  1139. context.deleteShader(vertexShader);
  1140. context.deleteShader(fragmentShader);
  1141. return shaderProgram;
  1142. };
  1143. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  1144. var results = [];
  1145. for (var index = 0; index < uniformsNames.length; index++) {
  1146. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  1147. }
  1148. return results;
  1149. };
  1150. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  1151. var results = [];
  1152. for (var index = 0; index < attributesNames.length; index++) {
  1153. try {
  1154. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  1155. }
  1156. catch (e) {
  1157. results.push(-1);
  1158. }
  1159. }
  1160. return results;
  1161. };
  1162. Engine.prototype.enableEffect = function (effect) {
  1163. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  1164. if (effect && effect.onBind) {
  1165. effect.onBind(effect);
  1166. }
  1167. return;
  1168. }
  1169. this._vertexAttribArraysToUse = this._vertexAttribArraysToUse || [];
  1170. this._vertexAttribArraysEnabled = this._vertexAttribArraysEnabled || [];
  1171. // Use program
  1172. this.setProgram(effect.getProgram());
  1173. var i, ul;
  1174. for (i = 0, ul = this._vertexAttribArraysToUse.length; i < ul; i++) {
  1175. this._vertexAttribArraysToUse[i] = false;
  1176. }
  1177. var attributesCount = effect.getAttributesCount();
  1178. for (i = 0; i < attributesCount; i++) {
  1179. // Attributes
  1180. var order = effect.getAttributeLocation(i);
  1181. if (order >= 0) {
  1182. this._vertexAttribArraysToUse[order] = true;
  1183. }
  1184. }
  1185. for (i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  1186. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArraysEnabled[i] || this._vertexAttribArraysToUse[i]) {
  1187. continue;
  1188. }
  1189. this._vertexAttribArraysEnabled[i] = false;
  1190. this._gl.disableVertexAttribArray(i);
  1191. }
  1192. for (i = 0, ul = this._vertexAttribArraysToUse.length; i < ul; i++) {
  1193. if (this._vertexAttribArraysToUse[i] && !this._vertexAttribArraysEnabled[i]) {
  1194. this._vertexAttribArraysEnabled[i] = true;
  1195. this._gl.enableVertexAttribArray(i);
  1196. }
  1197. }
  1198. this._currentEffect = effect;
  1199. if (effect.onBind) {
  1200. effect.onBind(effect);
  1201. }
  1202. };
  1203. Engine.prototype.setIntArray = function (uniform, array) {
  1204. if (!uniform)
  1205. return;
  1206. this._gl.uniform1iv(uniform, array);
  1207. };
  1208. Engine.prototype.setIntArray2 = function (uniform, array) {
  1209. if (!uniform || array.length % 2 !== 0)
  1210. return;
  1211. this._gl.uniform2iv(uniform, array);
  1212. };
  1213. Engine.prototype.setIntArray3 = function (uniform, array) {
  1214. if (!uniform || array.length % 3 !== 0)
  1215. return;
  1216. this._gl.uniform3iv(uniform, array);
  1217. };
  1218. Engine.prototype.setIntArray4 = function (uniform, array) {
  1219. if (!uniform || array.length % 4 !== 0)
  1220. return;
  1221. this._gl.uniform4iv(uniform, array);
  1222. };
  1223. Engine.prototype.setFloatArray = function (uniform, array) {
  1224. if (!uniform)
  1225. return;
  1226. this._gl.uniform1fv(uniform, array);
  1227. };
  1228. Engine.prototype.setFloatArray2 = function (uniform, array) {
  1229. if (!uniform || array.length % 2 !== 0)
  1230. return;
  1231. this._gl.uniform2fv(uniform, array);
  1232. };
  1233. Engine.prototype.setFloatArray3 = function (uniform, array) {
  1234. if (!uniform || array.length % 3 !== 0)
  1235. return;
  1236. this._gl.uniform3fv(uniform, array);
  1237. };
  1238. Engine.prototype.setFloatArray4 = function (uniform, array) {
  1239. if (!uniform || array.length % 4 !== 0)
  1240. return;
  1241. this._gl.uniform4fv(uniform, array);
  1242. };
  1243. Engine.prototype.setArray = function (uniform, array) {
  1244. if (!uniform)
  1245. return;
  1246. this._gl.uniform1fv(uniform, array);
  1247. };
  1248. Engine.prototype.setArray2 = function (uniform, array) {
  1249. if (!uniform || array.length % 2 !== 0)
  1250. return;
  1251. this._gl.uniform2fv(uniform, array);
  1252. };
  1253. Engine.prototype.setArray3 = function (uniform, array) {
  1254. if (!uniform || array.length % 3 !== 0)
  1255. return;
  1256. this._gl.uniform3fv(uniform, array);
  1257. };
  1258. Engine.prototype.setArray4 = function (uniform, array) {
  1259. if (!uniform || array.length % 4 !== 0)
  1260. return;
  1261. this._gl.uniform4fv(uniform, array);
  1262. };
  1263. Engine.prototype.setMatrices = function (uniform, matrices) {
  1264. if (!uniform)
  1265. return;
  1266. this._gl.uniformMatrix4fv(uniform, false, matrices);
  1267. };
  1268. Engine.prototype.setMatrix = function (uniform, matrix) {
  1269. if (!uniform)
  1270. return;
  1271. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  1272. };
  1273. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  1274. if (!uniform)
  1275. return;
  1276. this._gl.uniformMatrix3fv(uniform, false, matrix);
  1277. };
  1278. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  1279. if (!uniform)
  1280. return;
  1281. this._gl.uniformMatrix2fv(uniform, false, matrix);
  1282. };
  1283. Engine.prototype.setFloat = function (uniform, value) {
  1284. if (!uniform)
  1285. return;
  1286. this._gl.uniform1f(uniform, value);
  1287. };
  1288. Engine.prototype.setFloat2 = function (uniform, x, y) {
  1289. if (!uniform)
  1290. return;
  1291. this._gl.uniform2f(uniform, x, y);
  1292. };
  1293. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  1294. if (!uniform)
  1295. return;
  1296. this._gl.uniform3f(uniform, x, y, z);
  1297. };
  1298. Engine.prototype.setBool = function (uniform, bool) {
  1299. if (!uniform)
  1300. return;
  1301. this._gl.uniform1i(uniform, bool);
  1302. };
  1303. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  1304. if (!uniform)
  1305. return;
  1306. this._gl.uniform4f(uniform, x, y, z, w);
  1307. };
  1308. Engine.prototype.setColor3 = function (uniform, color3) {
  1309. if (!uniform)
  1310. return;
  1311. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  1312. };
  1313. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  1314. if (!uniform)
  1315. return;
  1316. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  1317. };
  1318. // States
  1319. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  1320. if (zOffset === void 0) { zOffset = 0; }
  1321. if (reverseSide === void 0) { reverseSide = false; }
  1322. // Culling
  1323. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  1324. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  1325. var cullFace = this.cullBackFaces ? showSide : hideSide;
  1326. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  1327. if (culling) {
  1328. this._depthCullingState.cullFace = cullFace;
  1329. this._depthCullingState.cull = true;
  1330. }
  1331. else {
  1332. this._depthCullingState.cull = false;
  1333. }
  1334. }
  1335. // Z offset
  1336. this._depthCullingState.zOffset = zOffset;
  1337. };
  1338. Engine.prototype.setDepthBuffer = function (enable) {
  1339. this._depthCullingState.depthTest = enable;
  1340. };
  1341. Engine.prototype.getDepthWrite = function () {
  1342. return this._depthCullingState.depthMask;
  1343. };
  1344. Engine.prototype.setDepthWrite = function (enable) {
  1345. this._depthCullingState.depthMask = enable;
  1346. };
  1347. Engine.prototype.setColorWrite = function (enable) {
  1348. this._gl.colorMask(enable, enable, enable, enable);
  1349. };
  1350. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  1351. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  1352. if (this._alphaMode === mode) {
  1353. return;
  1354. }
  1355. switch (mode) {
  1356. case Engine.ALPHA_DISABLE:
  1357. this._alphaState.alphaBlend = false;
  1358. break;
  1359. case Engine.ALPHA_COMBINE:
  1360. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  1361. this._alphaState.alphaBlend = true;
  1362. break;
  1363. case Engine.ALPHA_ONEONE:
  1364. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1365. this._alphaState.alphaBlend = true;
  1366. break;
  1367. case Engine.ALPHA_ADD:
  1368. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1369. this._alphaState.alphaBlend = true;
  1370. break;
  1371. case Engine.ALPHA_SUBTRACT:
  1372. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  1373. this._alphaState.alphaBlend = true;
  1374. break;
  1375. case Engine.ALPHA_MULTIPLY:
  1376. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  1377. this._alphaState.alphaBlend = true;
  1378. break;
  1379. case Engine.ALPHA_MAXIMIZED:
  1380. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  1381. this._alphaState.alphaBlend = true;
  1382. break;
  1383. }
  1384. if (!noDepthWriteChange) {
  1385. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  1386. }
  1387. this._alphaMode = mode;
  1388. };
  1389. Engine.prototype.getAlphaMode = function () {
  1390. return this._alphaMode;
  1391. };
  1392. Engine.prototype.setAlphaTesting = function (enable) {
  1393. this._alphaTest = enable;
  1394. };
  1395. Engine.prototype.getAlphaTesting = function () {
  1396. return this._alphaTest;
  1397. };
  1398. // Textures
  1399. Engine.prototype.wipeCaches = function () {
  1400. this.resetTextureCache();
  1401. this._currentEffect = null;
  1402. this._stencilState.reset();
  1403. this._depthCullingState.reset();
  1404. this.setDepthFunctionToLessOrEqual();
  1405. this._alphaState.reset();
  1406. this._cachedVertexBuffers = null;
  1407. this._cachedIndexBuffer = null;
  1408. this._cachedEffectForVertexBuffers = null;
  1409. };
  1410. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  1411. var gl = this._gl;
  1412. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  1413. var magFilter = gl.NEAREST;
  1414. var minFilter = gl.NEAREST;
  1415. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  1416. magFilter = gl.LINEAR;
  1417. minFilter = gl.LINEAR;
  1418. }
  1419. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  1420. magFilter = gl.LINEAR;
  1421. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  1422. }
  1423. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  1424. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  1425. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  1426. texture.samplingMode = samplingMode;
  1427. };
  1428. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  1429. var _this = this;
  1430. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  1431. if (onLoad === void 0) { onLoad = null; }
  1432. if (onError === void 0) { onError = null; }
  1433. if (buffer === void 0) { buffer = null; }
  1434. var texture = this._gl.createTexture();
  1435. var extension;
  1436. var fromData = false;
  1437. if (url.substr(0, 5) === "data:") {
  1438. fromData = true;
  1439. }
  1440. if (!fromData)
  1441. extension = url.substr(url.length - 4, 4).toLowerCase();
  1442. else {
  1443. var oldUrl = url;
  1444. fromData = oldUrl.split(':');
  1445. url = oldUrl;
  1446. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  1447. }
  1448. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  1449. var isTGA = (extension === ".tga");
  1450. scene._addPendingData(texture);
  1451. texture.url = url;
  1452. texture.noMipmap = noMipmap;
  1453. texture.references = 1;
  1454. texture.samplingMode = samplingMode;
  1455. this._loadedTexturesCache.push(texture);
  1456. var onerror = function () {
  1457. scene._removePendingData(texture);
  1458. if (onError) {
  1459. onError();
  1460. }
  1461. };
  1462. var callback;
  1463. if (isTGA) {
  1464. callback = function (arrayBuffer) {
  1465. var data = new Uint8Array(arrayBuffer);
  1466. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  1467. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  1468. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  1469. }, onLoad, samplingMode);
  1470. };
  1471. if (!(fromData instanceof Array))
  1472. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  1473. callback(arrayBuffer);
  1474. }, onerror, scene.database, true);
  1475. else
  1476. callback(buffer);
  1477. }
  1478. else if (isDDS) {
  1479. callback = function (data) {
  1480. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  1481. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  1482. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  1483. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  1484. }, onLoad, samplingMode);
  1485. };
  1486. if (!(fromData instanceof Array))
  1487. BABYLON.Tools.LoadFile(url, function (data) {
  1488. callback(data);
  1489. }, onerror, scene.database, true);
  1490. else
  1491. callback(buffer);
  1492. }
  1493. else {
  1494. var onload = function (img) {
  1495. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  1496. var isPot = (img.width === potWidth && img.height === potHeight);
  1497. if (!isPot) {
  1498. _this._prepareWorkingCanvas();
  1499. _this._workingCanvas.width = potWidth;
  1500. _this._workingCanvas.height = potHeight;
  1501. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  1502. _this._workingContext.imageSmoothingEnabled = false;
  1503. _this._workingContext.mozImageSmoothingEnabled = false;
  1504. _this._workingContext.oImageSmoothingEnabled = false;
  1505. _this._workingContext.webkitImageSmoothingEnabled = false;
  1506. _this._workingContext.msImageSmoothingEnabled = false;
  1507. }
  1508. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  1509. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  1510. _this._workingContext.imageSmoothingEnabled = true;
  1511. _this._workingContext.mozImageSmoothingEnabled = true;
  1512. _this._workingContext.oImageSmoothingEnabled = true;
  1513. _this._workingContext.webkitImageSmoothingEnabled = true;
  1514. _this._workingContext.msImageSmoothingEnabled = true;
  1515. }
  1516. }
  1517. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  1518. }, onLoad, samplingMode);
  1519. };
  1520. if (!(fromData instanceof Array))
  1521. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  1522. else
  1523. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  1524. }
  1525. return texture;
  1526. };
  1527. Engine.prototype._getInternalFormat = function (format) {
  1528. var internalFormat = this._gl.RGBA;
  1529. switch (format) {
  1530. case Engine.TEXTUREFORMAT_ALPHA:
  1531. internalFormat = this._gl.ALPHA;
  1532. break;
  1533. case Engine.TEXTUREFORMAT_LUMINANCE:
  1534. internalFormat = this._gl.LUMINANCE;
  1535. break;
  1536. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  1537. internalFormat = this._gl.LUMINANCE_ALPHA;
  1538. break;
  1539. case Engine.TEXTUREFORMAT_RGB:
  1540. internalFormat = this._gl.RGB;
  1541. break;
  1542. case Engine.TEXTUREFORMAT_RGBA:
  1543. internalFormat = this._gl.RGBA;
  1544. break;
  1545. }
  1546. return internalFormat;
  1547. };
  1548. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  1549. if (compression === void 0) { compression = null; }
  1550. var internalFormat = this._getInternalFormat(format);
  1551. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  1552. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  1553. if (texture._width % 4 !== 0) {
  1554. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  1555. }
  1556. if (compression) {
  1557. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  1558. }
  1559. else {
  1560. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  1561. }
  1562. if (texture.generateMipMaps) {
  1563. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1564. }
  1565. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  1566. this.resetTextureCache();
  1567. texture.isReady = true;
  1568. };
  1569. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  1570. if (compression === void 0) { compression = null; }
  1571. var texture = this._gl.createTexture();
  1572. texture._baseWidth = width;
  1573. texture._baseHeight = height;
  1574. texture._width = width;
  1575. texture._height = height;
  1576. texture.references = 1;
  1577. this.updateRawTexture(texture, data, format, invertY, compression);
  1578. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  1579. // Filters
  1580. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  1581. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1582. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1583. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  1584. texture.samplingMode = samplingMode;
  1585. this._loadedTexturesCache.push(texture);
  1586. return texture;
  1587. };
  1588. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  1589. var texture = this._gl.createTexture();
  1590. texture._baseWidth = width;
  1591. texture._baseHeight = height;
  1592. if (generateMipMaps) {
  1593. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  1594. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  1595. }
  1596. this.resetTextureCache();
  1597. texture._width = width;
  1598. texture._height = height;
  1599. texture.isReady = false;
  1600. texture.generateMipMaps = generateMipMaps;
  1601. texture.references = 1;
  1602. texture.samplingMode = samplingMode;
  1603. this.updateTextureSamplingMode(samplingMode, texture);
  1604. this._loadedTexturesCache.push(texture);
  1605. return texture;
  1606. };
  1607. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  1608. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  1609. if (texture.isCube) {
  1610. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  1611. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1612. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1613. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  1614. }
  1615. else {
  1616. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  1617. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1618. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1619. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  1620. }
  1621. };
  1622. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  1623. if (premulAlpha === void 0) { premulAlpha = false; }
  1624. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  1625. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  1626. if (premulAlpha) {
  1627. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  1628. }
  1629. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  1630. if (texture.generateMipMaps) {
  1631. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1632. }
  1633. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  1634. this.resetTextureCache();
  1635. texture.isReady = true;
  1636. };
  1637. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  1638. if (texture._isDisabled) {
  1639. return;
  1640. }
  1641. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  1642. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  1643. try {
  1644. // Testing video texture support
  1645. if (this._videoTextureSupported === undefined) {
  1646. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  1647. if (this._gl.getError() !== 0) {
  1648. this._videoTextureSupported = false;
  1649. }
  1650. else {
  1651. this._videoTextureSupported = true;
  1652. }
  1653. }
  1654. // Copy video through the current working canvas if video texture is not supported
  1655. if (!this._videoTextureSupported) {
  1656. if (!texture._workingCanvas) {
  1657. texture._workingCanvas = document.createElement("canvas");
  1658. texture._workingContext = texture._workingCanvas.getContext("2d");
  1659. texture._workingCanvas.width = texture._width;
  1660. texture._workingCanvas.height = texture._height;
  1661. }
  1662. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  1663. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  1664. }
  1665. else {
  1666. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  1667. }
  1668. if (texture.generateMipMaps) {
  1669. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1670. }
  1671. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  1672. this.resetTextureCache();
  1673. texture.isReady = true;
  1674. }
  1675. catch (ex) {
  1676. // Something unexpected
  1677. // Let's disable the texture
  1678. texture._isDisabled = true;
  1679. }
  1680. };
  1681. Engine.prototype.createRenderTargetTexture = function (size, options) {
  1682. // old version had a "generateMipMaps" arg instead of options.
  1683. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  1684. // in the same way, generateDepthBuffer is defaulted to true
  1685. var generateMipMaps = false;
  1686. var generateDepthBuffer = true;
  1687. var generateStencilBuffer = false;
  1688. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  1689. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1690. if (options !== undefined) {
  1691. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  1692. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  1693. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  1694. type = options.type === undefined ? type : options.type;
  1695. if (options.samplingMode !== undefined) {
  1696. samplingMode = options.samplingMode;
  1697. }
  1698. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  1699. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  1700. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  1701. }
  1702. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  1703. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  1704. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  1705. }
  1706. }
  1707. var gl = this._gl;
  1708. var texture = gl.createTexture();
  1709. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  1710. var width = size.width || size;
  1711. var height = size.height || size;
  1712. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  1713. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  1714. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  1715. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  1716. }
  1717. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  1718. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  1719. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1720. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1721. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  1722. var depthStencilBuffer;
  1723. // Create the depth/stencil buffer
  1724. if (generateStencilBuffer) {
  1725. depthStencilBuffer = gl.createRenderbuffer();
  1726. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  1727. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  1728. }
  1729. else if (generateDepthBuffer) {
  1730. depthStencilBuffer = gl.createRenderbuffer();
  1731. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  1732. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  1733. }
  1734. // Create the framebuffer
  1735. var framebuffer = gl.createFramebuffer();
  1736. this.bindUnboundFramebuffer(framebuffer);
  1737. // Manage attachments
  1738. if (generateStencilBuffer) {
  1739. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  1740. }
  1741. else if (generateDepthBuffer) {
  1742. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  1743. }
  1744. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  1745. if (generateMipMaps) {
  1746. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1747. }
  1748. // Unbind
  1749. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  1750. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  1751. this.bindUnboundFramebuffer(null);
  1752. texture._framebuffer = framebuffer;
  1753. if (generateDepthBuffer) {
  1754. texture._depthBuffer = depthStencilBuffer;
  1755. }
  1756. texture._baseWidth = width;
  1757. texture._baseHeight = height;
  1758. texture._width = width;
  1759. texture._height = height;
  1760. texture.isReady = true;
  1761. texture.generateMipMaps = generateMipMaps;
  1762. texture.references = 1;
  1763. texture.samplingMode = samplingMode;
  1764. texture.type = type;
  1765. this.resetTextureCache();
  1766. this._loadedTexturesCache.push(texture);
  1767. return texture;
  1768. };
  1769. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  1770. var gl = this._gl;
  1771. var texture = gl.createTexture();
  1772. var generateMipMaps = true;
  1773. var generateDepthBuffer = true;
  1774. var generateStencilBuffer = false;
  1775. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1776. if (options !== undefined) {
  1777. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  1778. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  1779. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  1780. if (options.samplingMode !== undefined) {
  1781. samplingMode = options.samplingMode;
  1782. }
  1783. }
  1784. texture.isCube = true;
  1785. texture.references = 1;
  1786. texture.generateMipMaps = generateMipMaps;
  1787. texture.references = 1;
  1788. texture.samplingMode = samplingMode;
  1789. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  1790. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  1791. for (var face = 0; face < 6; face++) {
  1792. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  1793. }
  1794. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  1795. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  1796. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1797. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1798. // Create the depth buffer
  1799. var depthStencilBuffer;
  1800. // Create the depth/stencil buffer
  1801. if (generateStencilBuffer) {
  1802. depthStencilBuffer = gl.createRenderbuffer();
  1803. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  1804. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  1805. }
  1806. else if (generateDepthBuffer) {
  1807. depthStencilBuffer = gl.createRenderbuffer();
  1808. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  1809. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  1810. }
  1811. // Create the framebuffer
  1812. var framebuffer = gl.createFramebuffer();
  1813. this.bindUnboundFramebuffer(framebuffer);
  1814. // Manage attachments
  1815. if (generateStencilBuffer) {
  1816. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  1817. }
  1818. else if (generateDepthBuffer) {
  1819. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  1820. }
  1821. // Mipmaps
  1822. if (texture.generateMipMaps) {
  1823. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  1824. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1825. }
  1826. // Unbind
  1827. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  1828. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  1829. this.bindUnboundFramebuffer(null);
  1830. texture._framebuffer = framebuffer;
  1831. if (generateDepthBuffer) {
  1832. texture._depthBuffer = depthStencilBuffer;
  1833. }
  1834. texture._width = size;
  1835. texture._height = size;
  1836. texture.isReady = true;
  1837. this.resetTextureCache();
  1838. this._loadedTexturesCache.push(texture);
  1839. return texture;
  1840. };
  1841. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  1842. var _this = this;
  1843. var gl = this._gl;
  1844. var texture = gl.createTexture();
  1845. texture.isCube = true;
  1846. texture.url = rootUrl;
  1847. texture.references = 1;
  1848. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  1849. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  1850. if (isDDS) {
  1851. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  1852. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  1853. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  1854. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  1855. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  1856. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  1857. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  1858. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1859. }
  1860. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1861. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  1862. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1863. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1864. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  1865. _this.resetTextureCache();
  1866. texture._width = info.width;
  1867. texture._height = info.height;
  1868. texture.isReady = true;
  1869. }, null, null, true);
  1870. }
  1871. else {
  1872. cascadeLoad(rootUrl, scene, function (imgs) {
  1873. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  1874. var height = width;
  1875. _this._prepareWorkingCanvas();
  1876. _this._workingCanvas.width = width;
  1877. _this._workingCanvas.height = height;
  1878. var faces = [
  1879. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  1880. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  1881. ];
  1882. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  1883. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  1884. for (var index = 0; index < faces.length; index++) {
  1885. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  1886. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  1887. }
  1888. if (!noMipmap) {
  1889. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1890. }
  1891. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1892. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  1893. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1894. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1895. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  1896. _this.resetTextureCache();
  1897. texture._width = width;
  1898. texture._height = height;
  1899. texture.isReady = true;
  1900. }, files);
  1901. }
  1902. return texture;
  1903. };
  1904. Engine.prototype.updateTextureSize = function (texture, width, height) {
  1905. texture._width = width;
  1906. texture._height = height;
  1907. texture._size = width * height;
  1908. texture._baseWidth = width;
  1909. texture._baseHeight = height;
  1910. };
  1911. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  1912. var _this = this;
  1913. var gl = this._gl;
  1914. var texture = gl.createTexture();
  1915. scene._addPendingData(texture);
  1916. texture.isCube = true;
  1917. texture.references = 1;
  1918. texture.url = url;
  1919. var internalFormat = this._getInternalFormat(format);
  1920. var textureType = gl.UNSIGNED_BYTE;
  1921. if (type === Engine.TEXTURETYPE_FLOAT) {
  1922. textureType = gl.FLOAT;
  1923. }
  1924. var width = size;
  1925. var height = width;
  1926. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  1927. texture._width = width;
  1928. texture._height = height;
  1929. var onerror = function () {
  1930. scene._removePendingData(texture);
  1931. };
  1932. var internalCallback = function (data) {
  1933. var rgbeDataArrays = callback(data);
  1934. var facesIndex = [
  1935. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  1936. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  1937. ];
  1938. width = texture._width;
  1939. height = texture._height;
  1940. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  1941. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  1942. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  1943. if (!noMipmap && isPot) {
  1944. if (mipmmapGenerator) {
  1945. var arrayTemp = [];
  1946. // Data are known to be in +X +Y +Z -X -Y -Z
  1947. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  1948. arrayTemp.push(rgbeDataArrays[0]); // +X
  1949. arrayTemp.push(rgbeDataArrays[3]); // -X
  1950. arrayTemp.push(rgbeDataArrays[1]); // +Y
  1951. arrayTemp.push(rgbeDataArrays[4]); // -Y
  1952. arrayTemp.push(rgbeDataArrays[2]); // +Z
  1953. arrayTemp.push(rgbeDataArrays[5]); // -Z
  1954. var mipData = mipmmapGenerator(arrayTemp);
  1955. for (var level = 0; level < mipData.length; level++) {
  1956. var mipSize = width >> level;
  1957. // mipData is order in +X -X +Y -Y +Z -Z
  1958. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  1959. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  1960. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  1961. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  1962. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  1963. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  1964. }
  1965. }
  1966. else {
  1967. // Data are known to be in +X +Y +Z -X -Y -Z
  1968. for (var index = 0; index < facesIndex.length; index++) {
  1969. var faceData = rgbeDataArrays[index];
  1970. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  1971. }
  1972. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1973. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  1974. // By following the webgl standard changes from Revision 7, 2014/11/24
  1975. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  1976. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  1977. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  1978. // Data are known to be in +X +Y +Z -X -Y -Z
  1979. for (var index = 0; index < facesIndex.length; index++) {
  1980. var faceData = rgbeDataArrays[index];
  1981. // Create a new RGBA Face.
  1982. var newFaceData = new Float32Array(width * height * 4);
  1983. for (var x = 0; x < width; x++) {
  1984. for (var y = 0; y < height; y++) {
  1985. var index_1 = (y * width + x) * 3;
  1986. var newIndex = (y * width + x) * 4;
  1987. // Map Old Value to new value.
  1988. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  1989. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  1990. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  1991. // Add fully opaque alpha channel.
  1992. newFaceData[newIndex + 3] = 1;
  1993. }
  1994. }
  1995. // Reupload the face.
  1996. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  1997. }
  1998. // Try to generate mipmap again.
  1999. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2000. }
  2001. }
  2002. }
  2003. else {
  2004. noMipmap = true;
  2005. }
  2006. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  2007. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  2008. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  2009. }
  2010. else if (textureType === HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  2011. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  2012. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  2013. }
  2014. else {
  2015. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2016. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  2017. }
  2018. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2019. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2020. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2021. texture.isReady = true;
  2022. _this.resetTextureCache();
  2023. scene._removePendingData(texture);
  2024. };
  2025. BABYLON.Tools.LoadFile(url, function (data) {
  2026. internalCallback(data);
  2027. }, onerror, scene.database, true);
  2028. return texture;
  2029. };
  2030. ;
  2031. Engine.prototype._releaseTexture = function (texture) {
  2032. var gl = this._gl;
  2033. if (texture._framebuffer) {
  2034. gl.deleteFramebuffer(texture._framebuffer);
  2035. }
  2036. if (texture._depthBuffer) {
  2037. gl.deleteRenderbuffer(texture._depthBuffer);
  2038. }
  2039. gl.deleteTexture(texture);
  2040. // Unbind channels
  2041. this.unbindAllTextures();
  2042. var index = this._loadedTexturesCache.indexOf(texture);
  2043. if (index !== -1) {
  2044. this._loadedTexturesCache.splice(index, 1);
  2045. }
  2046. };
  2047. Engine.prototype.setProgram = function (program) {
  2048. if (this._currentProgram !== program) {
  2049. this._gl.useProgram(program);
  2050. this._currentProgram = program;
  2051. }
  2052. };
  2053. Engine.prototype.bindSamplers = function (effect) {
  2054. this.setProgram(effect.getProgram());
  2055. var samplers = effect.getSamplers();
  2056. for (var index = 0; index < samplers.length; index++) {
  2057. var uniform = effect.getUniform(samplers[index]);
  2058. this._gl.uniform1i(uniform, index);
  2059. }
  2060. this._currentEffect = null;
  2061. };
  2062. Engine.prototype.activateTexture = function (texture) {
  2063. if (this._activeTexture !== texture) {
  2064. this._gl.activeTexture(texture);
  2065. this._activeTexture = texture;
  2066. }
  2067. };
  2068. Engine.prototype._bindTextureDirectly = function (target, texture) {
  2069. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  2070. this._gl.bindTexture(target, texture);
  2071. this._activeTexturesCache[this._activeTexture] = texture;
  2072. }
  2073. };
  2074. Engine.prototype._bindTexture = function (channel, texture) {
  2075. if (channel < 0) {
  2076. return;
  2077. }
  2078. this.activateTexture(this._gl["TEXTURE" + channel]);
  2079. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  2080. };
  2081. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  2082. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  2083. };
  2084. Engine.prototype.unbindAllTextures = function () {
  2085. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  2086. this.activateTexture(this._gl["TEXTURE" + channel]);
  2087. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2088. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  2089. }
  2090. };
  2091. Engine.prototype.setTexture = function (channel, uniform, texture) {
  2092. if (channel < 0) {
  2093. return;
  2094. }
  2095. this._gl.uniform1i(uniform, channel);
  2096. this._setTexture(channel, texture);
  2097. };
  2098. Engine.prototype._setTexture = function (channel, texture) {
  2099. // Not ready?
  2100. if (!texture || !texture.isReady()) {
  2101. if (this._activeTexturesCache[channel] != null) {
  2102. this.activateTexture(this._gl["TEXTURE" + channel]);
  2103. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2104. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  2105. }
  2106. return;
  2107. }
  2108. // Video
  2109. var alreadyActivated = false;
  2110. if (texture instanceof BABYLON.VideoTexture) {
  2111. this.activateTexture(this._gl["TEXTURE" + channel]);
  2112. alreadyActivated = true;
  2113. texture.update();
  2114. }
  2115. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  2116. texture.delayLoad();
  2117. return;
  2118. }
  2119. var internalTexture = texture.getInternalTexture();
  2120. if (this._activeTexturesCache[channel] === internalTexture) {
  2121. return;
  2122. }
  2123. if (!alreadyActivated) {
  2124. this.activateTexture(this._gl["TEXTURE" + channel]);
  2125. }
  2126. if (internalTexture.isCube) {
  2127. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  2128. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  2129. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  2130. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  2131. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  2132. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  2133. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  2134. }
  2135. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  2136. }
  2137. else {
  2138. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  2139. if (internalTexture._cachedWrapU !== texture.wrapU) {
  2140. internalTexture._cachedWrapU = texture.wrapU;
  2141. switch (texture.wrapU) {
  2142. case BABYLON.Texture.WRAP_ADDRESSMODE:
  2143. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  2144. break;
  2145. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  2146. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  2147. break;
  2148. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  2149. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  2150. break;
  2151. }
  2152. }
  2153. if (internalTexture._cachedWrapV !== texture.wrapV) {
  2154. internalTexture._cachedWrapV = texture.wrapV;
  2155. switch (texture.wrapV) {
  2156. case BABYLON.Texture.WRAP_ADDRESSMODE:
  2157. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  2158. break;
  2159. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  2160. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  2161. break;
  2162. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  2163. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  2164. break;
  2165. }
  2166. }
  2167. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  2168. }
  2169. };
  2170. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  2171. if (channel < 0) {
  2172. return;
  2173. }
  2174. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  2175. this._textureUnits = new Int32Array(textures.length);
  2176. }
  2177. for (var i = 0; i < textures.length; i++) {
  2178. this._textureUnits[i] = channel + i;
  2179. }
  2180. this._gl.uniform1iv(uniform, this._textureUnits);
  2181. for (var index = 0; index < textures.length; index++) {
  2182. this._setTexture(channel + index, textures[index]);
  2183. }
  2184. };
  2185. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  2186. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  2187. var value = texture.anisotropicFilteringLevel;
  2188. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  2189. value = 1;
  2190. }
  2191. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  2192. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  2193. texture._cachedAnisotropicFilteringLevel = value;
  2194. }
  2195. };
  2196. Engine.prototype.readPixels = function (x, y, width, height) {
  2197. var data = new Uint8Array(height * width * 4);
  2198. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  2199. return data;
  2200. };
  2201. /**
  2202. * Add an externaly attached data from its key.
  2203. * This method call will fail and return false, if such key already exists.
  2204. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  2205. * @param key the unique key that identifies the data
  2206. * @param data the data object to associate to the key for this Engine instance
  2207. * @return true if no such key were already present and the data was added successfully, false otherwise
  2208. */
  2209. Engine.prototype.addExternalData = function (key, data) {
  2210. return this._externalData.add(key, data);
  2211. };
  2212. /**
  2213. * Get an externaly attached data from its key
  2214. * @param key the unique key that identifies the data
  2215. * @return the associated data, if present (can be null), or undefined if not present
  2216. */
  2217. Engine.prototype.getExternalData = function (key) {
  2218. return this._externalData.get(key);
  2219. };
  2220. /**
  2221. * Get an externaly attached data from its key, create it using a factory if it's not already present
  2222. * @param key the unique key that identifies the data
  2223. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  2224. * @return the associated data, can be null if the factory returned null.
  2225. */
  2226. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  2227. return this._externalData.getOrAddWithFactory(key, factory);
  2228. };
  2229. /**
  2230. * Remove an externaly attached data from the Engine instance
  2231. * @param key the unique key that identifies the data
  2232. * @return true if the data was successfully removed, false if it doesn't exist
  2233. */
  2234. Engine.prototype.removeExternalData = function (key) {
  2235. return this._externalData.remove(key);
  2236. };
  2237. Engine.prototype.releaseInternalTexture = function (texture) {
  2238. if (!texture) {
  2239. return;
  2240. }
  2241. texture.references--;
  2242. // Final reference ?
  2243. if (texture.references === 0) {
  2244. var texturesCache = this.getLoadedTexturesCache();
  2245. var index = texturesCache.indexOf(texture);
  2246. if (index > -1) {
  2247. texturesCache.splice(index, 1);
  2248. }
  2249. this._releaseTexture(texture);
  2250. }
  2251. };
  2252. // Dispose
  2253. Engine.prototype.dispose = function () {
  2254. this.hideLoadingUI();
  2255. this.stopRenderLoop();
  2256. // Release scenes
  2257. while (this.scenes.length) {
  2258. this.scenes[0].dispose();
  2259. }
  2260. // Release audio engine
  2261. Engine.audioEngine.dispose();
  2262. // Release effects
  2263. for (var name in this._compiledEffects) {
  2264. this._gl.deleteProgram(this._compiledEffects[name]._program);
  2265. }
  2266. // Unbind
  2267. if (this._vertexAttribArraysEnabled) {
  2268. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  2269. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArraysEnabled[i]) {
  2270. continue;
  2271. }
  2272. this._gl.disableVertexAttribArray(i);
  2273. }
  2274. }
  2275. this._gl = null;
  2276. // Events
  2277. window.removeEventListener("blur", this._onBlur);
  2278. window.removeEventListener("focus", this._onFocus);
  2279. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  2280. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  2281. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  2282. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  2283. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  2284. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  2285. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  2286. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  2287. };
  2288. // Loading screen
  2289. Engine.prototype.displayLoadingUI = function () {
  2290. this._loadingScreen.displayLoadingUI();
  2291. };
  2292. Engine.prototype.hideLoadingUI = function () {
  2293. this._loadingScreen.hideLoadingUI();
  2294. };
  2295. Object.defineProperty(Engine.prototype, "loadingScreen", {
  2296. get: function () {
  2297. return this._loadingScreen;
  2298. },
  2299. set: function (loadingScreen) {
  2300. this._loadingScreen = loadingScreen;
  2301. },
  2302. enumerable: true,
  2303. configurable: true
  2304. });
  2305. Object.defineProperty(Engine.prototype, "loadingUIText", {
  2306. set: function (text) {
  2307. this._loadingScreen.loadingUIText = text;
  2308. },
  2309. enumerable: true,
  2310. configurable: true
  2311. });
  2312. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  2313. set: function (color) {
  2314. this._loadingScreen.loadingUIBackgroundColor = color;
  2315. },
  2316. enumerable: true,
  2317. configurable: true
  2318. });
  2319. Engine.prototype.attachContextLostEvent = function (callback) {
  2320. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  2321. };
  2322. Engine.prototype.attachContextRestoredEvent = function (callback) {
  2323. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  2324. };
  2325. // FPS
  2326. Engine.prototype.getFps = function () {
  2327. return this.fps;
  2328. };
  2329. Engine.prototype.getDeltaTime = function () {
  2330. return this.deltaTime;
  2331. };
  2332. Engine.prototype._measureFps = function () {
  2333. this.previousFramesDuration.push(BABYLON.Tools.Now);
  2334. var length = this.previousFramesDuration.length;
  2335. if (length >= 2) {
  2336. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  2337. }
  2338. if (length >= this.fpsRange) {
  2339. if (length > this.fpsRange) {
  2340. this.previousFramesDuration.splice(0, 1);
  2341. length = this.previousFramesDuration.length;
  2342. }
  2343. var sum = 0;
  2344. for (var id = 0; id < length - 1; id++) {
  2345. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  2346. }
  2347. this.fps = 1000.0 / (sum / (length - 1));
  2348. }
  2349. };
  2350. Engine.prototype._canRenderToFloatTexture = function () {
  2351. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
  2352. };
  2353. Engine.prototype._canRenderToHalfFloatTexture = function () {
  2354. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
  2355. };
  2356. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  2357. Engine.prototype._canRenderToTextureOfType = function (format, extension) {
  2358. var tempcanvas = document.createElement("canvas");
  2359. tempcanvas.height = 16;
  2360. tempcanvas.width = 16;
  2361. var gl = (tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
  2362. // extension.
  2363. var ext = gl.getExtension(extension);
  2364. if (!ext) {
  2365. return false;
  2366. }
  2367. // setup GLSL program
  2368. var vertexCode = "attribute vec4 a_position;\n void main() {\n gl_Position = a_position;\n }";
  2369. var fragmentCode = "precision mediump float;\n uniform vec4 u_color;\n uniform sampler2D u_texture;\n\n void main() {\n gl_FragColor = texture2D(u_texture, vec2(0.5, 0.5)) * u_color;\n }";
  2370. var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
  2371. gl.useProgram(program);
  2372. // look up where the vertex data needs to go.
  2373. var positionLocation = gl.getAttribLocation(program, "a_position");
  2374. var colorLoc = gl.getUniformLocation(program, "u_color");
  2375. // provide texture coordinates for the rectangle.
  2376. var positionBuffer = gl.createBuffer();
  2377. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  2378. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  2379. -1.0, -1.0,
  2380. 1.0, -1.0,
  2381. -1.0, 1.0,
  2382. -1.0, 1.0,
  2383. 1.0, -1.0,
  2384. 1.0, 1.0]), gl.STATIC_DRAW);
  2385. gl.enableVertexAttribArray(positionLocation);
  2386. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  2387. var whiteTex = gl.createTexture();
  2388. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  2389. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
  2390. var tex = gl.createTexture();
  2391. gl.bindTexture(gl.TEXTURE_2D, tex);
  2392. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
  2393. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  2394. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  2395. var fb = gl.createFramebuffer();
  2396. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  2397. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
  2398. var cleanup = function () {
  2399. gl.deleteProgram(program);
  2400. gl.disableVertexAttribArray(positionLocation);
  2401. gl.deleteBuffer(positionBuffer);
  2402. gl.deleteFramebuffer(fb);
  2403. gl.deleteTexture(whiteTex);
  2404. gl.deleteTexture(tex);
  2405. };
  2406. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  2407. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  2408. BABYLON.Tools.Log("GL Support: can **NOT** render to " + format + " texture");
  2409. cleanup();
  2410. return false;
  2411. }
  2412. // Draw the rectangle.
  2413. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  2414. gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
  2415. gl.drawArrays(gl.TRIANGLES, 0, 6);
  2416. gl.bindTexture(gl.TEXTURE_2D, tex);
  2417. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  2418. gl.clearColor(1, 0, 0, 1);
  2419. gl.clear(gl.COLOR_BUFFER_BIT);
  2420. gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
  2421. gl.drawArrays(gl.TRIANGLES, 0, 6);
  2422. var pixel = new Uint8Array(4);
  2423. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  2424. if (pixel[0] !== 0 ||
  2425. pixel[1] < 248 ||
  2426. pixel[2] < 248 ||
  2427. pixel[3] < 254) {
  2428. BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
  2429. cleanup();
  2430. return false;
  2431. }
  2432. // Succesfully rendered to "format" texture.
  2433. cleanup();
  2434. return true;
  2435. };
  2436. // Statics
  2437. Engine.isSupported = function () {
  2438. try {
  2439. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  2440. if (navigator.isCocoonJS) {
  2441. return true;
  2442. }
  2443. var tempcanvas = document.createElement("canvas");
  2444. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  2445. return gl != null && !!window.WebGLRenderingContext;
  2446. }
  2447. catch (e) {
  2448. return false;
  2449. }
  2450. };
  2451. // Const statics
  2452. Engine._ALPHA_DISABLE = 0;
  2453. Engine._ALPHA_ADD = 1;
  2454. Engine._ALPHA_COMBINE = 2;
  2455. Engine._ALPHA_SUBTRACT = 3;
  2456. Engine._ALPHA_MULTIPLY = 4;
  2457. Engine._ALPHA_MAXIMIZED = 5;
  2458. Engine._ALPHA_ONEONE = 6;
  2459. Engine._DELAYLOADSTATE_NONE = 0;
  2460. Engine._DELAYLOADSTATE_LOADED = 1;
  2461. Engine._DELAYLOADSTATE_LOADING = 2;
  2462. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  2463. Engine._TEXTUREFORMAT_ALPHA = 0;
  2464. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  2465. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  2466. Engine._TEXTUREFORMAT_RGB = 4;
  2467. Engine._TEXTUREFORMAT_RGBA = 5;
  2468. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  2469. Engine._TEXTURETYPE_FLOAT = 1;
  2470. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  2471. // Updatable statics so stick with vars here
  2472. Engine.CollisionsEpsilon = 0.001;
  2473. Engine.CodeRepository = "src/";
  2474. Engine.ShadersRepository = "src/Shaders/";
  2475. return Engine;
  2476. })();
  2477. BABYLON.Engine = Engine;
  2478. })(BABYLON || (BABYLON = {}));