AHND-HTML5-Shipping.UE4.js 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377
  1. // javascript code used with Epic Games HTML5 projects
  2. //
  3. // much of this is for UE4 development purposes.
  4. //
  5. // to create a custom JS file for your project:
  6. // - make a copy of this file - or make one from scratch
  7. // - and put it in: "your project folder"/Build/HTML/GameX.js.template
  8. // ================================================================================
  9. // ================================================================================
  10. // stubbing in missing/un-supported functions
  11. // .../Engine/Source/Runtime/Engine/Private/ActiveSound.cpp
  12. // // for velocity-based effects like doppler
  13. // ParseParams.Velocity = (ParseParams.Transform.GetTranslation() - LastLocation) / DeltaTime;
  14. window.AudioContext = ( window.AudioContext || window.webkitAudioContext || null );
  15. if ( AudioContext ) {
  16. var ue4_hacks = {}; // making this obvious...
  17. ue4_hacks.ctx = new AudioContext();
  18. ue4_hacks.panner = ue4_hacks.ctx.createPanner();
  19. ue4_hacks.panner.__proto__.setVelocity = ( ue4_hacks.panner.__proto__.setVelocity || function(){} );
  20. }
  21. // ================================================================================
  22. // ================================================================================
  23. // project configuration
  24. // Minimum WebGL version that the page needs in order to run. UE4 will attempt to use WebGL 2 if available.
  25. // Set this to 1 to run with a WebGL 1 fallback if the graphical features required by your UE4 project are
  26. // low enough that they do not strictly require WebGL 2.
  27. const requiredWebGLVersion = 1;
  28. const targetOffscreenCanvas = false;
  29. // Add ?webgl1 GET param to explicitly test the WebGL 1 fallback version even if browser does support WebGL 2.
  30. const explicitlyUseWebGL1 = (location.search.indexOf('webgl1') != -1);
  31. // "Project Settings" -> Platforms -> HTML5 -> Packaging -> "Compress files during shipping packaging"
  32. // When hosting UE4 builds live on a production CDN, compression should always be enabled,
  33. // since uncompressed files are too huge to be downloaded over the web.
  34. // Please view tip in "Project Setting" for more information.
  35. const serveCompressedAssets = false;
  36. // "Project Settings" -> Project -> Packaging -> "Use Pak File"
  37. // For the large .data file, there's two ways to manage compression: either UE4 UnrealPak tool can compress it in engine, or
  38. // it can be gzip compressed on disk like other assets. Compressing via UnrealPak has the advantage of storing a smaller data
  39. // file to IndexedDB, whereas gzip compressing to disk has the advantage of starting up the page slightly faster.
  40. // If true, serve out 'UE4Game.data.gz', if false, serve out 'UE4Game.data'.
  41. //const dataFileIsGzipCompressed = false;
  42. console.log("Emscripten version: 3.1.50");
  43. console.log("Emscripten configuration: ");
  44. // ================================================================================
  45. // *** HTML5 emscripten ***
  46. var Module = {
  47. // state management
  48. infoPrinted: false,
  49. lastcurrentDownloadedSize: 0,
  50. totalDependencies: 0,
  51. dataBytesStoredInIndexedDB: 0, // Track how much data is currently stored in IndexedDB.
  52. assetDownloadProgress: {}, // Track how many bytes of each needed asset has been downloaded so far.
  53. UE4_indexedDBName: 'UE4_assetDatabase_AHND', // this should be an ascii ID string without special characters that is unique to the project that is being packaged
  54. UE4_indexedDBVersion: 202410301954, // Bump this number to invalidate existing IDB storages in browsers.
  55. };
  56. // ================================================================================
  57. // *** HTML5 UE4 ***
  58. var sessionStorageCommandLine = null;
  59. // try to get the command line from a session storage key?
  60. if ('') {
  61. var sessionStorageCommandLine = window.sessionStorage.getItem('');
  62. //if (sessionStorageCommandLine) {
  63. // console.log("sessionStorageCommandLine: " + sessionStorageCommandLine);
  64. //}
  65. }
  66. Module.arguments = sessionStorageCommandLine != null ? [sessionStorageCommandLine] : ['../../../AHND/AHND.uproject','-stdout',];
  67. // UE4 Editor or UE4 Frontend with assets "cook on the fly"?
  68. if (location.host != "" && (location.search.indexOf('cookonthefly') != -1)) {
  69. Module.arguments.push("'-filehostIp=" + location.protocol + "//" + location.host + "'");
  70. }
  71. if ('') {
  72. var sessionStorageWebSocketUrl = window.sessionStorage.getItem('');
  73. //if (sessionStorageWebSocketUrl) {
  74. // console.log("sessionStorageWebSocketUrl: " + sessionStorageWebSocketUrl);
  75. //}
  76. Module['websocket'] = Module['websocket'] || {};
  77. Module['websocket']['url'] = sessionStorageWebSocketUrl;
  78. }
  79. var UE4 = {
  80. on_fatal: function() {
  81. try {
  82. UE4.on_fatal = Module.cwrap('on_fatal', null, ['string', 'string']);
  83. } catch(e) {
  84. UE4.on_fatal = function() {};
  85. }
  86. },
  87. ///////////////////////////////////////////////
  88. web_send_message: function (msg){
  89. try {
  90. UE4.web_send_message = Module.ccall('web_send_message', null, ['string','string']);
  91. } catch (e) {
  92. UE4.web_send_message = function (msg) { };;
  93. }
  94. },
  95. ///////////////////////////////////////////////*/
  96. };
  97. function searchtext() {
  98. var inputVal = document.getElementById('searchinput').value;
  99. console.log('input111111', inputVal);
  100. Module.ccall('web_send_message', null, ['string'], [encodeURI(inputVal)]);
  101. var myinpurBox = document.getElementById('inputbox')
  102. // 清空输入框的值
  103. document.getElementById('searchinput').value = '';
  104. myinpurBox.style.zIndex = "-6"
  105. }
  106. function debounce(func, wait) {
  107. let timeout;
  108. return function() {
  109. const context = this;
  110. const args = arguments;
  111. clearTimeout(timeout);
  112. timeout = setTimeout(function() {
  113. func.apply(context, args);
  114. }, wait);
  115. };
  116. }
  117. function myinput() {
  118. const searchInput = document.getElementById('searchinput');
  119. searchInput.addEventListener('input', debounce(function(event) {
  120. console.log('Input changed to: ' + event.target.value);
  121. var textData = event.target.value;
  122. Module.ccall('web_send_message', null, ['string'], [encodeURI(textData)]);
  123. }, 300)); // 300毫秒的延迟
  124. }
  125. myinput()
  126. function CCall()
  127. {
  128. //var data = Module.ccall('web_get_data','string');
  129. var data = "中文字符";
  130. //Module.ccall('web_set_data',null,['string'],['number'])
  131. Module.ccall('web_send_message',null,['string'],[encodeURI(data)]);
  132. }
  133. function closevideo() {
  134. var myVideoBox = document.getElementById("myVideoBox")
  135. console.log('knaknak2312',myVideoBox);
  136. myVideoBox.style.zIndex = "-1"
  137. var myVideo = document.getElementById("myVideo")
  138. myVideo.pause();
  139. myVideo.scr=''
  140. }
  141. // ----------------------------------------
  142. // UE4 error and logging
  143. document.addEventListener('error', function(){document.getElementById('clear_indexeddb').style.display = 'inline-block';}, false);
  144. function addLog(info, color) {
  145. $("#logwindow").append("<h4><small>" + info + " </small></h4>");
  146. }
  147. Module.print = addLog;
  148. Module.printErr = function(text) {
  149. console.error(text);
  150. };
  151. window.onerror = function(e) {
  152. e = e.toString();
  153. if (e.toLowerCase().indexOf('memory') != -1) {
  154. e += '<br>';
  155. if (!heuristic64BitBrowser) e += ' Try running in a 64-bit browser to resolve.';
  156. }
  157. showErrorDialog(e);
  158. }
  159. // ----------------------------------------
  160. // ----------------------------------------
  161. // detect wasm-threads
  162. function detectWasmThreads() {
  163. return WebAssembly.validate(new Uint8Array([
  164. 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x04, 0x01, 0x60,
  165. 0x00, 0x00, 0x03, 0x02, 0x01, 0x00, 0x05, 0x04, 0x01, 0x03, 0x01, 0x01,
  166. 0x0a, 0x0b, 0x01, 0x09, 0x00, 0x41, 0x01, 0xfe, 0x10, 0x02, 0x00, 0x1a,
  167. 0x0b
  168. ]));
  169. }
  170. Module['UE4_MultiThreaded'] = false && detectWasmThreads();
  171. // ================================================================================
  172. // ================================================================================
  173. // emscripten memory system
  174. // Tests if type === 'browser' or type === 'os' is 64-bit or not.
  175. function heuristicIs64Bit(type) {
  176. function contains(str, substrList) { for(var i in substrList) if (str.indexOf(substrList[i]) != -1) return true; return false; }
  177. var ua = (navigator.userAgent + ' ' + navigator.oscpu + ' ' + navigator.platform).toLowerCase();
  178. if (contains(ua, ['wow64'])) return type === 'os'; // 32bit browser on 64bit OS
  179. if (contains(ua, ['x86_64', 'amd64', 'ia64', 'win64', 'x64', 'arm64', 'irix64', 'mips64', 'ppc64', 'sparc64'])) return true;
  180. if (contains(ua, ['i386', 'i486', 'i586', 'i686', 'x86', 'arm7', 'android', 'mobile', 'win32'])) return false;
  181. if (contains(ua, ['intel mac os'])) return true;
  182. return false;
  183. }
  184. var heuristic64BitBrowser = heuristicIs64Bit('browser');
  185. // // For best stability on 32-bit browsers, allocate asm.js/WebAssembly heap up front before proceeding
  186. // // to load any other page content. This mitigates the chances that loading up page assets first would
  187. // // fragment the memory area of the browser process.
  188. // var pageSize = 64 * 1024;
  189. // function alignPageUp(size) { return pageSize * Math.ceil(size / pageSize); }
  190. //
  191. // // The absolute maximum that is possible is one memory page short of 2GB.
  192. // var MAX_MEMORY = Module['UE4_MultiThreaded']
  193. // ? 512 * 1024 * 1024 // multi threaded - non-growable
  194. // : 2048 * 1024 * 1024 - pageSize; // single threaded - growable
  195. //
  196. // // note: 32-bit browsers (single threaded) needs to start at 32MB
  197. // var MIN_MEMORY = Module['UE4_MultiThreaded']
  198. // ? 512 * 1024 * 1024 // multi threaded - non-growable
  199. // : 32 * 1024 * 1024; // single threaded - growable
  200. //
  201. // function allocateHeap() {
  202. // Module['wasmMemory'] = new WebAssembly.Memory({ initial: MIN_MEMORY / pageSize, maximum: MAX_MEMORY / pageSize });
  203. // if (!Module['wasmMemory']||!Module['wasmMemory'].buffer) {
  204. // throw 'Out of memory';
  205. // }
  206. // Module['buffer'] = Module['wasmMemory'].buffer;
  207. // if (Module['buffer'].byteLength < MIN_MEMORY) {
  208. // delete Module['buffer'];
  209. // throw 'Out of memory';
  210. // }
  211. // Module['TOTAL_MEMORY'] = Module['buffer'].byteLength;
  212. // }
  213. // allocateHeap();
  214. // Module['MAX_MEMORY'] = MAX_MEMORY;
  215. //
  216. // function MB(x) { return (x/1024/1024) + 'MB'; }
  217. // console.log('Initial memory size: ' + MB(Module['TOTAL_MEMORY']) + ' (MIN_MEMORY: ' + MB(MIN_MEMORY) + ', MAX_MEMORY: ' + MB(MAX_MEMORY) + ', heuristic64BitBrowser: ' + heuristic64BitBrowser + ', heuristic64BitOS: ' + heuristicIs64Bit('os') + ')');
  218. // ================================================================================
  219. // WebGL
  220. Module['preinitializedWebGLContext'] = null;
  221. Module['canvas'] = document.getElementById('canvas');
  222. function getGpuInfo() {
  223. var gl = Module['preinitializedWebGLContext'];
  224. if (!gl) return '(no GL: ' + Module['webGLErrorReason'] + ')';
  225. var glInfo = '';
  226. var debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
  227. if (debugInfo) glInfo += gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL) + ' ' + gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) + '/';
  228. glInfo += gl.getParameter(gl.VENDOR) + ' ' + gl.getParameter(gl.RENDERER);
  229. glInfo += ' ' + gl.getParameter(gl.VERSION);
  230. glInfo += ', ' + gl.getParameter(gl.SHADING_LANGUAGE_VERSION);
  231. if (Module['softwareWebGL']) glInfo += ' (software)';
  232. return glInfo;
  233. }
  234. function detectWebGL() {
  235. var canvas = targetOffscreenCanvas ? document.createElement("canvas") : (Module['canvas'] || document.createElement("canvas"));
  236. // If you run into problems with WebGL 2, or for quick testing purposes, you can disable UE4
  237. // from using WebGL 2 and revert back to WebGL 1 by setting the following flag to true.
  238. var disableWebGL2 = false;
  239. if (explicitlyUseWebGL1) {
  240. disableWebGL2 = true;
  241. console.log('Disabled WebGL 2 as requested by ?webgl1 GET param.');
  242. }
  243. var names = ["webgl", "experimental-webgl"];
  244. if (disableWebGL2) {
  245. WebGL2RenderingContext = undefined;
  246. } else {
  247. names = ["webgl2"].concat(names);
  248. }
  249. function testError(e) { Module['webGLErrorReason'] = e.statusMessage; };
  250. canvas.addEventListener("webglcontextcreationerror", testError, false);
  251. try {
  252. for(var failIfMajorPerformanceCaveat = 1; failIfMajorPerformanceCaveat >= 0; --failIfMajorPerformanceCaveat) {
  253. for(var i in names) {
  254. try {
  255. var context = canvas.getContext(names[i], {antialias:false,alpha:false,depth:true,stencil:true,failIfMajorPerformanceCaveat:!!failIfMajorPerformanceCaveat});
  256. Module['preinitializedWebGLContext'] = context;
  257. Module['softwareWebGL'] = !failIfMajorPerformanceCaveat;
  258. if (context && typeof context.getParameter == "function") {
  259. if (typeof WebGL2RenderingContext !== 'undefined' && context instanceof WebGL2RenderingContext && names[i] == 'webgl2') {
  260. return 2;
  261. } else {
  262. // We were able to precreate only a WebGL 1 context, remove support for WebGL 2 from the rest of the page execution.
  263. WebGL2RenderingContext = undefined;
  264. return 1;
  265. }
  266. }
  267. } catch(e) { Module['webGLErrorReason'] = e.toString(); }
  268. }
  269. }
  270. } finally {
  271. canvas.removeEventListener("webglcontextcreationerror", testError, false);
  272. if ( targetOffscreenCanvas ) {
  273. delete canvas;
  274. }
  275. }
  276. return 0;
  277. }
  278. // ----------------------------------------
  279. // ----------------------------------------
  280. // canvas - scaling
  281. // Canvas scaling mode should be set to one of: 1=STRETCH, 2=ASPECT, or 3=FIXED.
  282. // This dictates how the canvas size changes when the browser window is resized
  283. // by dragging from the corner.
  284. var canvasWindowedScaleMode = 1 /*STRETCH*/;
  285. // High DPI setting configures whether to match the canvas size 1:1 with
  286. // the physical pixels on the screen.
  287. // For background, see https://www.khronos.org/webgl/wiki/HandlingHighDPI
  288. var canvasWindowedUseHighDpi = true;
  289. // Stores the initial size of the canvas in physical pixel units.
  290. // If canvasWindowedScaleMode == 3 (FIXED), this size defines the fixed resolution
  291. // that the app will render to.
  292. // If canvasWindowedScaleMode == 2 (ASPECT), this size defines only the aspect ratio
  293. // that the canvas will be constrained to.
  294. // If canvasWindowedScaleMode == 1 (STRETCH), these size values are ignored.
  295. var canvasAspectRatioWidth = 1280; // 1366;
  296. var canvasAspectRatioHeight = 720; // 768;
  297. // The resizeCanvas() function recomputes the canvas size on the page as the user changes
  298. // the browser window size.
  299. function resizeCanvas(aboutToEnterFullscreen) {
  300. // Configuration variables, feel free to play around with these to tweak.
  301. var minimumCanvasHeightCssPixels = 480; // the visible size of the canvas should always be at least this high (in CSS pixels)
  302. var minimumCanvasHeightFractionOfBrowserWindowHeight = 1.0; // and also vertically take up this much % of the total browser client area height.
  303. if (aboutToEnterFullscreen && !aboutToEnterFullscreen.type) { // UE4 engine is calling this function right before entering fullscreen?
  304. // If you want to perform specific resolution setup here, do so by setting Module['canvas'].width x Module['canvas'].height now,
  305. // and configure Module['UE4_fullscreenXXX'] fields above. Most of the time, the defaults are good, so no need to resize here.
  306. // Return true here if you want to abort entering fullscreen mode altogether.
  307. return;
  308. }
  309. // The browser called resizeCanvas() to notify that we just entered fullscreen? In that case, we never react, since the strategy is
  310. // to always set the canvas size right before entering fullscreen.
  311. if (document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || document.msFullscreenElement) {
  312. return;
  313. }
  314. var mainArea = document.getElementById('mainarea');
  315. var mainAreaRect = mainArea.getBoundingClientRect();
  316. var buttonArea = document.getElementById('buttonarea');
  317. var buttonAreaRect = buttonArea.getBoundingClientRect();
  318. // Compute the unconstrained size for the div that encloses the canvas, in CSS pixel units.
  319. let width = document.documentElement.clientWidth;
  320. let height = document.documentElement.clientHeight;
  321. if (width > height) {
  322. var cssHeight = window.innerHeight;
  323. /////////////////////////////////////////////////
  324. var cssWidth = mainAreaRect.right - mainAreaRect.left;
  325. }else{
  326. var cssWidth = window.innerHeight;
  327. /////////////////////////////////////////////////
  328. var cssHeight = mainAreaRect.right - mainAreaRect.left;
  329. }
  330. {
  331. // Convert unconstrained render target size from CSS to physical pixel units.
  332. var newRenderTargetWidth = canvasWindowedUseHighDpi ? (cssWidth * window.devicePixelRatio) : cssWidth;
  333. var newRenderTargetHeight = canvasWindowedUseHighDpi ? (cssHeight * window.devicePixelRatio) : cssHeight;
  334. // WebGL render target sizes are always full integer pixels in size, so rounding is critical for CSS size computations below.
  335. newRenderTargetWidth = Math.round(newRenderTargetWidth);
  336. newRenderTargetHeight = Math.round(newRenderTargetHeight);
  337. }
  338. // Very subtle but important behavior is that the size of a DOM element on a web page in CSS pixel units can be a fraction, e.g. on
  339. // high DPI scaling displays (CSS pixel units are "virtual" pixels). If the CSS size and physical pixel size of the WebGL canvas do
  340. // not correspond to each other 1:1 after window.devicePixelRatio scaling has been applied, the result can look blurry. Therefore always
  341. // first compute the WebGL render target size first in physical pixels, and convert that back to CSS pixels so that the CSS pixel size
  342. // will perfectly align up and the result look clear without scaling applied.
  343. cssWidth = canvasWindowedUseHighDpi ? (newRenderTargetWidth / window.devicePixelRatio) : newRenderTargetWidth;
  344. cssHeight = canvasWindowedUseHighDpi ? (newRenderTargetHeight / window.devicePixelRatio) : newRenderTargetHeight;
  345. // Resize the actual Canvas element. Since this can either be a regular Canvas or an OffscreenCanvas, use an Emscripten API to
  346. // do the resizing, since it needs to be multithreading aware if an OffscreenCanvas is being used. In the case of an OffscreenCanvas,
  347. // the resizing may happen asynchronously.
  348. _emscripten_set_canvas_element_size(Module['canvas'].id, newRenderTargetWidth, newRenderTargetHeight);
  349. // emscripten_set_canvas_element_size_js(Module['canvas'].id, newRenderTargetWidth, newRenderTargetHeight);
  350. Module['canvas'].style.width = 100 + '%';
  351. Module['canvas'].style.height = 100 + '%';
  352. // Tell the engine that the web page has changed the size of the WebGL render target on the canvas (Module['canvas'].width/height).
  353. // This will update the GL viewport and propagate the change throughout the engine.
  354. // If the CSS style size is changed, this function doesn't need to be called.
  355. if (UE_JSlib.UE_CanvasSizeChanged) UE_JSlib.UE_CanvasSizeChanged();
  356. }
  357. Module['UE4_resizeCanvas'] = resizeCanvas;
  358. // Input event hooks: UE4 calls these functions for all input events it receives prior to handling the input event itself.
  359. // Use these functions if you need to override or hook into input handling on JavaScript side.
  360. // Possible return values from these functions:
  361. // 0: UE4 should process this input event, and use the default choice whether to suppress browser default navigation for the event.
  362. // 1: UE4 should process this input event, but not suppress browser default navigation for the event.
  363. // 2: UE4 should process this input event, and suppress browser default navigation for the event.
  364. // 3: UE4 should discard this input event, and use the default choice whether to suppress browser default navigation for the event.
  365. // 4: UE4 should discard this input event, but not suppress browser default navigation for the event.
  366. // 5: UE4 should discard this input event, and suppress browser default navigation for the event.
  367. Module['UE4_keyEvent'] = function(eventType, key, virtualKeyCode, domPhysicalKeyCode, keyEventStruct) { return 0; }
  368. Module['UE4_mouseEvent'] = function(eventType, x, y, button, buttons, mouseEventStruct) { return 0; }
  369. Module['UE4_wheelEvent'] = function(eventType, x, y, button, buttons, deltaX, deltaY, wheelEventStruct) { return 0; }
  370. // ----------------------------------------
  371. // ----------------------------------------
  372. // canvas - fullscreen
  373. // Fullscreen scaling mode behavior (export these to Module object for the engine to read)
  374. // This value is one of:
  375. // 0=NONE: The same canvas size is kept when entering fullscreen without change.
  376. // 1=STRETCH: The canvas is resized to the size of the whole screen, potentially changing aspect ratio.
  377. // 2=ASPECT: The canvas is resized to the size of the whole screen, but retaining current aspect ratio.
  378. // 3=FIXED: The canvas is centered on screen with a fixed resolution.
  379. Module['UE4_fullscreenScaleMode'] = 1;//canvasWindowedScaleMode; // BUG: if using FIXED, fullscreen gets some strange padding on margin...
  380. // When entering fullscreen mode, should UE4 engine resize the canvas?
  381. // 0=No resizing (do it manually in resizeCanvas()), 1=Resize to standard DPI, 2=Resize to highDPI
  382. Module['UE4_fullscreenCanvasResizeMode'] = canvasWindowedUseHighDpi ? 2/*HIDPI*/ : 1/*Standard DPI*/;
  383. // Specifies how canvas is scaled to fullscreen, if not rendering in 1:1 pixel perfect mode.
  384. // One of 0=Default, 1=Nearest, 2=Bilinear
  385. Module['UE4_fullscreenFilteringMode'] = 0;
  386. // ================================================================================
  387. // ================================================================================
  388. // IndexDB
  389. // NOTE: in a future release of UE4 - this whole section WILL GO AWAY (i.e. handled internally)
  390. var enableReadFromIndexedDB = (location.search.indexOf('noidbread') == -1);
  391. var enableWriteToIndexedDB = enableReadFromIndexedDB && (location.search.indexOf('noidbwrite') == -1);
  392. if (!enableReadFromIndexedDB) console.warn('Running with IndexedDB access disabled.');
  393. else if (!enableWriteToIndexedDB) console.warn('Running in read-only IndexedDB access mode.');
  394. function getIDBRequestErrorString(req) {
  395. try { return req.error ? ('IndexedDB ' + req.error.name + ': ' + req.error.message) : req.result;
  396. } catch(ex) { return null; }
  397. }
  398. function formatBytes(bytes) {
  399. if (bytes >= 1024*1024*1024) return (bytes / (1024*1024*1024)).toFixed(1) + ' GB';
  400. if (bytes >= 1024*1024) return (bytes / (1024*1024)).toFixed(0) + ' MB';
  401. if (bytes >= 1024) return (bytes / 1024).toFixed(1) + ' KB';
  402. return bytes + ' B';
  403. }
  404. function reportDataBytesStoredInIndexedDB(deltaBytes) {
  405. if (deltaBytes === null) Module['dataBytesStoredInIndexedDB'] = 0; // call with deltaBytes == null to report that DB was cleared.
  406. else Module['dataBytesStoredInIndexedDB'] += deltaBytes;
  407. document.getElementById('clear_indexeddb').title = 'Clear IndexedDB (' + formatBytes(Module['dataBytesStoredInIndexedDB']) + ')';
  408. }
  409. function deleteIndexedDBStorage(dbName, onsuccess, onerror, onblocked) {
  410. var idb = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
  411. if (Module['dbInstance']) Module['dbInstance'].close();
  412. if (!dbName) dbName = Module['UE4_indexedDBName'];
  413. var req = idb.deleteDatabase(dbName);
  414. req.onsuccess = function() { console.log('Deleted IndexedDB storage ' + dbName + '!'); reportDataBytesStoredInIndexedDB(null); if (onsuccess) onsuccess(); }
  415. req.onerror = function(evt) {
  416. var errorString = getIDBRequestErrorString(req);
  417. console.error('Failed to delete IndexedDB storage ' + dbName + ', ' + errorString);
  418. evt.preventDefault();
  419. if (onerror) onerror(errorString);
  420. };
  421. req.onblocked = function(evt) {
  422. var errorString = getIDBRequestErrorString(req);
  423. console.error('Failed to delete IndexedDB storage ' + dbName + ', DB was blocked! ' + errorString);
  424. evt.preventDefault();
  425. if (onblocked) onblocked(errorString);
  426. }
  427. }
  428. function storeToIndexedDB(db, key, value) {
  429. return new Promise(function(resolve, reject) {
  430. if (!enableWriteToIndexedDB) return reject('storeToIndexedDB: IndexedDB writes disabled by "?noidbwrite" option');
  431. function fail(e) {
  432. console.error('Failed to store file ' + key + ' to IndexedDB storage! error: ' + e);
  433. //if (!Module['idberrorShown']) {
  434. // showWarningRibbon('Failed to store file ' + key + ' to IndexedDB, error: ' + e);
  435. // Module['idberrorShown'] = true;
  436. //}
  437. return reject(e);
  438. }
  439. if (!db) return fail('IndexedDB not available!');
  440. if (location.protocol.indexOf('file') != -1) return reject('Loading via file://, skipping caching to IndexedDB');
  441. try {
  442. var transaction = db.transaction(['FILES'], 'readwrite');
  443. var packages = transaction.objectStore('FILES');
  444. var putRequest = packages.put(value, "file/" + Module.key + '/' + key);
  445. putRequest.onsuccess = function(evt) {
  446. if (value.byteLength || value.length) reportDataBytesStoredInIndexedDB(value.size || value.byteLength || value.length);
  447. resolve(key);
  448. };
  449. putRequest.onerror = function(evt) {
  450. var errorString = getIDBRequestErrorString(putRequest) || ('IndexedDB request error: ' + evt);
  451. evt.preventDefault();
  452. fail(errorString);
  453. };
  454. } catch(e) {
  455. fail(e);
  456. }
  457. });
  458. }
  459. function fetchFromIndexedDB(db, key) {
  460. return new Promise(function(resolve, reject) {
  461. if (!enableReadFromIndexedDB) return reject('fetchFromIndexedDB: IndexedDB reads disabled by "?noidbread" option');
  462. function fail(e) {
  463. console.error('Failed to read file ' + key + ' from IndexedDB storage! error:');
  464. console.error(e);
  465. //if (!Module['idberrorShown']) {
  466. // showWarningRibbon('Failed to read file ' + key + ' from IndexedDB, error: ' + e);
  467. // Module['idberrorShown'] = true;
  468. //}
  469. return reject(e);
  470. }
  471. if (!db) return fail('IndexedDB not available!');
  472. try {
  473. var transaction = db.transaction(['FILES'], 'readonly');
  474. var packages = transaction.objectStore('FILES');
  475. var getRequest = packages.get("file/" + Module.key + '/' + key);
  476. getRequest.onsuccess = function(evt) {
  477. if (evt.target.result) {
  478. var len = evt.target.result.size || evt.target.result.byteLength || evt.target.result.length;
  479. if (len) reportDataBytesStoredInIndexedDB(len);
  480. resolve(evt.target.result);
  481. } else {
  482. // Succeeded to load, but the load came back with the value of undefined, treat that as an error since we never store undefined in db.
  483. reject();
  484. }
  485. };
  486. getRequest.onerror = function(evt) {
  487. var errorString = getIDBRequestErrorString(getRequest) || ('IndexedDB.get request error: ' + evt);
  488. evt.preventDefault();
  489. fail(errorString);
  490. };
  491. } catch(e) {
  492. fail(e);
  493. }
  494. });
  495. }
  496. function fetchOrDownloadAndStore(db, url, responseType) {
  497. return new Promise(function(resolve, reject) {
  498. fetchFromIndexedDB(db, url)
  499. .then(function(data) { return resolve(data); })
  500. .catch(function(error) {
  501. return download(url, responseType)
  502. .then(function(data) {
  503. // Treat IDB store as separate operation that's not part of the Promise chain.
  504. /*return*/ storeToIndexedDB(db, url, data)
  505. .then(function() { return resolve(data); })
  506. .catch(function(error) {
  507. if ( enableReadFromIndexedDB || enableWriteToIndexedDB ) {
  508. console.error('Failed to store download to IndexedDB! ' + error);
  509. }
  510. return resolve(data); // succeeded download, but failed to store - ignore failure in that case and just proceed to run by calling the success handler.
  511. })
  512. })
  513. .catch(function(error) { return reject(error); })
  514. });
  515. });
  516. }
  517. function openIndexedDB(dbName, dbVersion) {
  518. return new Promise(function(resolve, reject) {
  519. if (!enableReadFromIndexedDB) return reject('openIndexedDB: IndexedDB disabled by "?noidbread" option');
  520. try {
  521. var idb = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
  522. var openRequest = idb.open(dbName, dbVersion);
  523. } catch(e) { return reject(e); }
  524. openRequest.onupgradeneeded = function(evt) {
  525. var db = evt.target.result;
  526. if (db.objectStoreNames.contains('FILES')) db.deleteObjectStore('FILES');
  527. db.createObjectStore('FILES');
  528. };
  529. openRequest.onsuccess = function(evt) {
  530. resolve(evt.target.result);
  531. };
  532. openRequest.onerror = function(evt) {
  533. var errorString = getIDBRequestErrorString(openRequest) || ('IndexedDB request error: ' + evt);
  534. evt.preventDefault();
  535. reject(errorString);
  536. };
  537. });
  538. }
  539. // Module.locateFile() routes asset downloads to either gzip compressed or uncompressed assets.
  540. Module.locateFile = function(name) {
  541. var serveGzipped = serveCompressedAssets;
  542. // When serving from file:// URLs, don't read .gz compressed files, because these files can't be transparently uncompressed.
  543. var isFileProtocol = name.indexOf('file://') != -1 || location.protocol.indexOf('file') != -1;
  544. if (isFileProtocol) {
  545. if (!Module['shownFileProtocolWarning']) {
  546. showWarningRibbon('Attempting to load the page via the "file://" protocol. This only works in Firefox, and even there only when not using compression, so attempting to load uncompressed assets. Please host the page on a web server and visit it via a "http://" URL.');
  547. Module['shownFileProtocolWarning'] = true;
  548. }
  549. serveGzipped = false;
  550. }
  551. // uncompressing very large gzip files may slow down startup times.
  552. // if (!dataFileIsGzipCompressed && name.split('.').slice(-1)[0] == 'data') serveGzipped = false;
  553. return serveGzipped ? (name + '.gz') : name;
  554. };
  555. // see site/source/docs/api_reference/module.rst for details
  556. Module.getPreloadedPackage = function(remotePackageName, remotePackageSize) {
  557. return Module['preloadedPackages'] ? Module['preloadedPackages'][remotePackageName] : null;
  558. }
  559. // ================================================================================
  560. // COMPILER
  561. // ----------------------------------------
  562. // wasm
  563. Module['instantiateWasm'] = function(info, receiveInstance) {
  564. Module['wasmDownloadAction'].then(function(downloadResults) {
  565. taskProgress(TASK_COMPILING);
  566. var wasmInstantiate = WebAssembly.instantiate(downloadResults.wasmModule || new Uint8Array(downloadResults.wasmBytes), info);
  567. return wasmInstantiate.then(function(output) {
  568. var instance = output.instance || output;
  569. var module = output.module;
  570. taskFinished(TASK_COMPILING);
  571. Module['wasmInstantiateActionResolve'](instance);
  572. receiveInstance(instance, module);
  573. // After a successful instantiation, attempt to save the compiled Wasm Module object to IndexedDB.
  574. if (!downloadResults.fromIndexedDB) {
  575. storeToIndexedDB(downloadResults.db, 'wasmModule', module).catch(function() {
  576. // If the browser did not support storing Wasm Modules to IndexedDB, try to store the Wasm instance instead.
  577. return storeToIndexedDB(downloadResults.db, 'wasmBytes', downloadResults.wasmBytes);
  578. });
  579. }
  580. });
  581. }).catch(function(error) {
  582. $ ('#mainarea').empty();
  583. $ ('#mainarea').append('<div class="alert alert-danger centered-axis-xy" style ="min-height: 10pt" role="alert">WebAssembly instantiation failed: <br> ' + error + '</div></div>');
  584. });
  585. return {};
  586. }
  587. // ----------------------------------------
  588. // shaders
  589. function compileShadersFromJson(jsonData) {
  590. var shaderPrograms = [];
  591. if (jsonData instanceof ArrayBuffer) jsonData = new TextDecoder('utf-8').decode(new DataView(jsonData));
  592. var programsDict = JSON.parse(jsonData);
  593. for(var i in programsDict) {
  594. shaderPrograms.push(programsDict[i]);
  595. }
  596. var gl = Module['preinitializedWebGLContext'];
  597. Module['precompiledShaders'] = [];
  598. Module['precompiledPrograms'] = [];
  599. Module['glIDCounter'] = 1;
  600. Module['precompiledUniforms'] = [null];
  601. var promise = new Promise(function(resolve, reject) {
  602. var nextProgramToBuild = 0;
  603. function buildProgram() {
  604. if (nextProgramToBuild >= shaderPrograms.length) {
  605. taskFinished(TASK_SHADERS);
  606. return resolve();
  607. }
  608. var p = shaderPrograms[nextProgramToBuild++];
  609. taskProgress(TASK_SHADERS, {current: nextProgramToBuild, total: shaderPrograms.length });
  610. var program = gl.createProgram();
  611. function lineNumberize(str) {
  612. str = str.split('\n');
  613. for(var i = 0; i < str.length; ++i) str[i] = (i<9?' ':'') + (i<99?' ':'') + (i+1) + ': ' + str[i];
  614. return str.join('\n');
  615. }
  616. var vs = gl.createShader(gl.VERTEX_SHADER);
  617. gl.shaderSource(vs, p.vs);
  618. gl.compileShader(vs);
  619. var success = gl.getShaderParameter(vs, gl.COMPILE_STATUS);
  620. var compileLog = gl.getShaderInfoLog(vs);
  621. if (compileLog) compileLog = compileLog.trim();
  622. if (compileLog) console.error('Compiling vertex shader: ' + lineNumberize(p.vs));
  623. if (!success) console.error('Vertex shader compilation failed!');
  624. if (compileLog) console.error('Compilation log: ' + compileLog);
  625. if (!success) return reject('Vertex shader compilation failed: ' + compileLog);
  626. gl.attachShader(program, vs);
  627. Module['precompiledShaders'].push({
  628. vs: p.vs,
  629. shader: vs,
  630. program: program
  631. });
  632. var fs = gl.createShader(gl.FRAGMENT_SHADER);
  633. gl.shaderSource(fs, p.fs);
  634. gl.compileShader(fs);
  635. var success = gl.getShaderParameter(fs, gl.COMPILE_STATUS);
  636. var compileLog = gl.getShaderInfoLog(fs);
  637. if (compileLog) compileLog = compileLog.trim();
  638. if (compileLog) console.error('Compiling fragment shader: ' + lineNumberize(p.fs));
  639. if (!success) console.error('Fragment shader compilation failed!');
  640. if (compileLog) console.error('Compilation log: ' + compileLog);
  641. if (!success) return reject('Fragment shader compilation failed: ' + compileLog);
  642. gl.attachShader(program, fs);
  643. Module['precompiledShaders'].push({
  644. fs: p.fs,
  645. shader: fs,
  646. program: program
  647. });
  648. for(var name in p.attribs) {
  649. gl.bindAttribLocation(program, p.attribs[name], name);
  650. }
  651. gl.linkProgram(program);
  652. var success = gl.getProgramParameter(program, gl.LINK_STATUS);
  653. var linkLog = gl.getProgramInfoLog(program);
  654. if (linkLog) linkLog = linkLog.trim();
  655. if (linkLog) console.error('Linking shader program, vs: \n' + lineNumberize(p.vs) + ', \n fs:\n' + lineNumberize(p.fs));
  656. if (!success) console.error('Shader program linking failed!');
  657. if (linkLog) console.error('Link log: ' + linkLog);
  658. if (!success) return reject('Shader linking failed: ' + linkLog);
  659. var ptable = {
  660. uniforms: {},
  661. maxUniformLength: 0,
  662. maxAttributeLength: -1,
  663. maxUniformBlockNameLength: -1
  664. };
  665. var GLctx = gl;
  666. var utable = ptable.uniforms;
  667. var numUniforms = GLctx.getProgramParameter(program, GLctx.ACTIVE_UNIFORMS);
  668. for (var i = 0; i < numUniforms; ++i) {
  669. var u = GLctx.getActiveUniform(program, i);
  670. var name = u.name;
  671. ptable.maxUniformLength = Math.max(ptable.maxUniformLength, name.length + 1);
  672. if (name.indexOf("]", name.length - 1) !== -1) {
  673. var ls = name.lastIndexOf("[");
  674. name = name.slice(0, ls);
  675. }
  676. var loc = GLctx.getUniformLocation(program, name);
  677. var id = Module['glIDCounter']++;
  678. utable[name] = [ u.size, id ];
  679. Module['precompiledUniforms'].push(loc);
  680. if (Module['precompiledUniforms'].length != Module['glIDCounter']) throw 'uniforms array not in sync! ' + Module['precompiledUniforms'].length + ', ' + Module['glIDCounter'];
  681. for (var j = 1; j < u.size; ++j) {
  682. var n = name + "[" + j + "]";
  683. loc = GLctx.getUniformLocation(program, n);
  684. id = Module['glIDCounter']++;
  685. Module['precompiledUniforms'].push(loc);
  686. if (Module['precompiledUniforms'].length != Module['glIDCounter']) throw 'uniforms array not in sync! ' + Module['precompiledUniforms'].length + ', ' + Module['glIDCounter'];
  687. }
  688. }
  689. var e = gl.getError();
  690. if (e) {
  691. console.error('Precompiling shaders got GL error: ' + e);
  692. return reject('Precompiling shaders got GL error: ' + e);
  693. }
  694. Module['precompiledPrograms'].push({
  695. program: program,
  696. programInfos: ptable,
  697. vs: p.vs,
  698. fs: p.fs
  699. });
  700. setTimeout(buildProgram, 0);
  701. }
  702. setTimeout(buildProgram, 0);
  703. })
  704. return promise;
  705. }
  706. // ================================================================================
  707. // download project files and progress handlers
  708. var TASK_DOWNLOADING = 0;
  709. var TASK_COMPILING = 1;
  710. var TASK_SHADERS = 2;
  711. var TASK_MAIN = 3;
  712. var loadTasks = [ 'Downloading', 'Compiling WebAssembly', 'Building shaders', 'Launching engine'];
  713. // // 节流函数
  714. // function throttle(func, limit) {
  715. // let inThrottle;
  716. // return function() {
  717. // const args = arguments;
  718. // const context = this;
  719. // if (!inThrottle) {
  720. // func.apply(context, args);
  721. // inThrottle = true;
  722. // setTimeout(() => inThrottle = false, limit);
  723. // }
  724. // }
  725. // }
  726. // 封装的进度更新函数,使用节流方式调用
  727. // const throttledCircleProgress = throttle(function(progressValue) {
  728. // console.log('jieliu====>',progressValue);
  729. // var newjindu=document.getElementById('newjindu')
  730. // newjindu.style.width = `${progressValue}%`;
  731. // }, 100); // 100毫秒的节流时间
  732. let timeindex =0
  733. let oneTime=null
  734. let nowTime=null
  735. function taskProgress(taskId, progress) {
  736. console.log('到这里===5',progress);
  737. var c = document.getElementById('compilingmessage');
  738. // var jingdubox=document.getElementById('progressBarBox')
  739. var jingdu = document.getElementById('progressBar2');
  740. var newjindubox = document.getElementById('newjindubox');
  741. var jingdu2 = document.getElementById('progressBar3');
  742. jingdu2.innerHTML='加载中'
  743. if (c) c.style.display = 'block';
  744. else return;
  745. var l = document.getElementById('load_' + taskId);
  746. if (!l) {
  747. var tasks = document.getElementById('loadTasks');
  748. if (!tasks) return;
  749. l = document.createElement('div');
  750. l.innerHTML = '<span id="icon_' + taskId + '" class="glyphicon glyphicon-refresh glyphicon-spin"></span> <span id="load_' + taskId + '"></span>';
  751. tasks.appendChild(l);
  752. l = document.getElementById('load_' + taskId);
  753. }
  754. if (!l.startTime) l.startTime = performance.now();
  755. var text = loadTasks[taskId];
  756. if (progress && progress.total) {
  757. if (timeindex==0) {
  758. oneTime=Date.now();
  759. }
  760. nowTime=Date.now()
  761. // if (jingdubox) jingdubox.style.display = 'block';
  762. if (newjindubox) newjindubox.style.display = 'block';
  763. if (jingdu) jingdu.style.display = 'block';
  764. jingdu2.innerHTML='下载资源中'
  765. text += ': ' + (progress.currentShow || progress.current) + '/' + (progress.totalShow || progress.total) + ' (' + (progress.current * 100 / progress.total).toFixed(0) + '%)';
  766. // throttledCircleProgress((progress.current * 100 / progress.total).toFixed(0) / 100);
  767. console.log('加载进度--',(progress.current * 100 / progress.total).toFixed(0));
  768. var a1=(progress.current * 100 / progress.total).toFixed(0) +"%"
  769. var a2=(progress.current * 100 / progress.total).toFixed(0)
  770. console.log('加载进度--222',a2);
  771. if (nowTime-oneTime>2000) {
  772. jingdu.innerHTML=a1
  773. var newjindu=document.getElementById('newjindu')
  774. newjindu.style.width = `${a2}%`;
  775. }
  776. if ((progress.current * 100 / progress.total).toFixed(0)==100) {
  777. jingdu2.innerHTML='加载中'
  778. timeindex=null
  779. }
  780. timeindex++
  781. } else {
  782. text += '...';
  783. }
  784. l.innerHTML = text;
  785. }
  786. function taskFinished(taskId, error) {
  787. var l = document.getElementById('load_' + taskId);
  788. var icon = document.getElementById('icon_' + taskId);
  789. if (l && icon) {
  790. var totalTime = performance.now() - l.startTime;
  791. if (!error) {
  792. l.innerHTML = loadTasks[taskId] + ' (' + (totalTime/1000).toFixed(2) + 's)';
  793. icon.className = 'glyphicon glyphicon-ok';
  794. }
  795. else {
  796. l.innerHTML = loadTasks[taskId] + ': FAILED! ' + error;
  797. icon.className = 'glyphicon glyphicon-remove';
  798. showErrorDialog(loadTasks[taskId] + ' failed: <br> ' + error);
  799. }
  800. }
  801. }
  802. function reportDownloadProgress(url, downloadedBytes, totalBytes, finished) {
  803. Module['assetDownloadProgress'][url] = {
  804. current: downloadedBytes,
  805. total: totalBytes,
  806. finished: finished
  807. };
  808. var aggregated = {
  809. current: 0,
  810. total: 0,
  811. finished: true
  812. };
  813. for(var i in Module['assetDownloadProgress']) {
  814. aggregated.current += Module['assetDownloadProgress'][i].current;
  815. aggregated.total += Module['assetDownloadProgress'][i].total;
  816. aggregated.finished = aggregated.finished && Module['assetDownloadProgress'][i].finished;
  817. }
  818. aggregated.currentShow = formatBytes(aggregated.current);
  819. aggregated.totalShow = formatBytes(aggregated.total);
  820. if (aggregated.finished) taskFinished(TASK_DOWNLOADING);
  821. else taskProgress(TASK_DOWNLOADING, aggregated);
  822. }
  823. function download(url, responseType) {
  824. return new Promise(function(resolve, reject) {
  825. var xhr = new XMLHttpRequest();
  826. xhr.open('GET', url, true);
  827. xhr.responseType = responseType || 'blob';
  828. reportDownloadProgress(url, 0, 1);
  829. xhr.onload = function() {
  830. if (xhr.status == 0 || (xhr.status >= 200 && xhr.status < 300)) {
  831. var len = xhr.response.size || xhr.response.byteLength;
  832. reportDownloadProgress(url, len, len, true);
  833. // try to use DecompressionStream to decompress the data in the case where header was not set properly?
  834. if (url.endsWith('gz') && xhr.getResponseHeader('Content-Encoding') != 'gzip' && typeof(DecompressionStream) == 'function' && (xhr.responseType == 'blob' || xhr.responseType == 'arraybuffer')) {
  835. //console.warn('Using DecompressionStream to decompress ' + xhr.responseType + ' of gzipped file ' + url);
  836. var readableStream = xhr.responseType == 'blob' ? xhr.response.stream() : new Response(xhr.response).body;
  837. //console.warn(readableStream);
  838. var decompressedReadableStream = readableStream.pipeThrough(new DecompressionStream('gzip'));
  839. //console.warn(decompressedReadableStream);
  840. var response = new Response(decompressedReadableStream);
  841. //console.warn(response);
  842. var promise = xhr.responseType == 'blob' ? response.blob() : response.arrayBuffer();
  843. //console.warn(result);
  844. return promise.then(function(data) {
  845. //console.warn('data');
  846. //console.warn(data);
  847. resolve(data);
  848. });
  849. }
  850. resolve(xhr.response);
  851. } else {
  852. taskFinished(TASK_DOWNLOADING, 'HTTP error ' + (xhr.status || 404) + ' ' + xhr.statusText + ' on file ' + url);
  853. reject({
  854. status: xhr.status,
  855. statusText: xhr.statusText
  856. });
  857. }
  858. };
  859. var contentLength = 1;
  860. xhr.onprogress = function(p) {
  861. reportDownloadProgress(url, p.loaded, p.lengthComputable ? p.total : contentLength);
  862. };
  863. xhr.onerror = function(e) {
  864. var isFileProtocol = url.indexOf('file://') == 0 || location.protocol.indexOf('file') != -1;
  865. if (isFileProtocol) taskFinished(TASK_DOWNLOADING, 'HTTP error ' + (xhr.status || 404) + ' ' + xhr.statusText + ' on file ' + url +'<br>Try using a web server to avoid loading via a "file://" URL.'); // Convert the most common source of errors to a more friendly message format.
  866. else taskFinished(TASK_DOWNLOADING, 'HTTP error ' + (xhr.status || 404) + ' ' + xhr.statusText + ' on file ' + url);
  867. reject({
  868. status: xhr.status || 404,
  869. statusText: xhr.statusText
  870. });
  871. };
  872. xhr.onreadystatechange = function() {
  873. if (xhr.readyState == xhr.HEADERS_RECEIVED) {
  874. contentLength = Number(xhr.getResponseHeader('Content-Length')) || 1;
  875. if (url.endsWith('gz') && (xhr.status == 0 || xhr.status == 200)) {
  876. if (xhr.getResponseHeader('Content-Encoding') != 'gzip') {
  877. // A fallback is to set serveCompressedAssets = false to serve uncompressed assets instead, but that is not really recommended for production use, since gzip compression shrinks
  878. // download sizes so dramatically that omitting it for production is not a good idea.
  879. if (typeof(DecompressionStream) == 'function' && (xhr.responseType == 'blob' || xhr.responseType == 'arraybuffer')) {
  880. // DecompressionStream browser functionality is available so we will try decompressing it once download is complete - but warn anyway as it is better to use the header
  881. console.warn('Downloaded a compressed file ' + url + ' without the necessary HTTP response header "Content-Encoding: gzip" specified!\nPlease configure gzip compression on this asset on the web server to serve gzipped assets!\nThis browser supports DecompressionStream so decompression will be attempted as a workaround.');
  882. } else {
  883. taskFinished(TASK_DOWNLOADING, 'Downloaded a compressed file ' + url + ' without the necessary HTTP response header "Content-Encoding: gzip" specified!<br>Please configure gzip compression on this asset on the web server to serve gzipped assets!<br>This browser does not appear to support DecompressionStream so decompression will not be attempted as a workaround.');
  884. xhr.onload = xhr.onprogress = xhr.onerror = xhr.onreadystatechange = null; // Abandon tracking events from this XHR further.
  885. xhr.abort();
  886. return reject({
  887. status: 406,
  888. statusText: 'Not Acceptable'
  889. });
  890. }
  891. }
  892. // After enabling Content-Encoding: gzip, make sure that the appropriate MIME type is being used for the asset, i.e. the MIME
  893. // type should be that of the uncompressed asset, and not the MIME type of the compression method that was used.
  894. if (xhr.getResponseHeader('Content-Type').toLowerCase().indexOf('zip') != -1) {
  895. function expectedMimeType(url) {
  896. if (url.indexOf('.wasm') != -1) return 'application/wasm';
  897. if (url.indexOf('.js') != -1) return 'application/javascript';
  898. return 'application/octet-stream';
  899. }
  900. console.warn('Downloaded a compressed file ' + url + ' with incorrect HTTP response header "Content-Type: ' + xhr.getResponseHeader('Content-Type') + '"!\nPlease set the MIME type of the asset to "' + expectedMimeType(url) + '".');
  901. //taskFinished(TASK_DOWNLOADING, 'Downloaded a compressed file ' + url + ' with incorrect HTTP response header "Content-Type: ' + xhr.getResponseHeader('Content-Type') + '"!<br>Please set the MIME type of the asset to "' + expectedMimeType(url) + '".');
  902. //xhr.onload = xhr.onprogress = xhr.onerror = xhr.onreadystatechange = null; // Abandon tracking events from this XHR further.
  903. //xhr.abort();
  904. //return reject({
  905. // status: 406,
  906. // statusText: 'Not Acceptable'
  907. //});
  908. }
  909. }
  910. }
  911. }
  912. xhr.send(null);
  913. });
  914. }
  915. // ================================================================================
  916. // ================================================================================
  917. // UE4 DEFAULT UX TEMPLATE
  918. function showErrorDialog(errorText) {
  919. // if ( errorText.indexOf('SyntaxError: ') != -1 ) { // this may be due to caching issue -- otherwise, compile time would have caught this
  920. // errorText = "NOTE: attempting to flush cache and force reload...<br>Please standby...";
  921. // setTimeout(function() {
  922. // location.reload(true);
  923. // }, 2000); // 2 seconds
  924. // }
  925. console.error('error: ' + errorText);
  926. var existingErrorDialog = document.getElementById('errorDialog');
  927. if (existingErrorDialog) {
  928. existingErrorDialog.innerHTML += '<br>' + errorText;
  929. } else {
  930. $('#mainarea').empty();
  931. $('#mainarea').append('<div class="alert alert-danger centered-axis-xy" style ="min-height: 10pt" role="alert" id="errorDialog">' + errorText + '</div></div>');
  932. }
  933. }
  934. function showWarningRibbon(warningText) {
  935. var existingWarningDialog = document.getElementById('warningDialog');
  936. if (existingWarningDialog) {
  937. existingWarningDialog.innerHTML += '<br>' + warningText;
  938. } else {
  939. $('#buttonrow').prepend('<div class="alert alert-warning centered-axis-x" role="warning" id="warningDialog" style="padding-top:5px; padding-bottom: 5px">' + warningText + '</div></div>');
  940. }
  941. }
  942. // Given a blob, asynchronously reads the byte contents of that blob to an arraybuffer and returns it as a Promise.
  943. function readBlobToArrayBuffer(blob) {
  944. return new Promise(function(resolve, reject) {
  945. var fileReader = new FileReader();
  946. fileReader.onload = function() { resolve(this.result); }
  947. fileReader.onerror = function(e) { reject(e); }
  948. fileReader.readAsArrayBuffer(blob);
  949. });
  950. }
  951. // Asynchronously appends the given script code to DOM. This is to ensure that
  952. // browsers parse and compile the JS code parallel to all other execution.
  953. function addScriptToDom(scriptCode) {
  954. return new Promise(function(resolve, reject) {
  955. var script = document.createElement('script');
  956. var blob = (scriptCode instanceof Blob) ? scriptCode : new Blob([scriptCode], { type: 'text/javascript' });
  957. var objectUrl = URL.createObjectURL(blob);
  958. script.src = objectUrl;
  959. script.onload = function() {
  960. script.onload = script.onerror = null; // Remove these onload and onerror handlers, because these capture the inputs to the Promise and the input function, which would leak a lot of memory!
  961. URL.revokeObjectURL(objectUrl); // Free up the blob. Note that for debugging purposes, this can be useful to comment out to be able to read the sources in debugger.
  962. resolve();
  963. }
  964. script.onerror = function(e) {
  965. script.onload = script.onerror = null; // Remove these onload and onerror handlers, because these capture the inputs to the Promise and the input function, which would leak a lot of memory!
  966. URL.revokeObjectURL(objectUrl);
  967. console.error('script failed to add to dom: ' + e);
  968. console.error(scriptCode);
  969. console.error(e);
  970. // The onerror event sends a DOM Level 3 event error object, which does not seem to have any kind of human readable error reason (https://developer.mozilla.org/en-US/docs/Web/Events/error)
  971. // There is another error event object at https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent, which would have an error reason. Perhaps that error event might sometimes be fired,
  972. // but if not, guess that the error reason was an OOM, since we are dealing with large .js files.
  973. reject(e.message || "(out of memory?)");
  974. }
  975. document.body.appendChild(script);
  976. });
  977. }
  978. // ----------------------------------------
  979. // ----------------------------------------
  980. // Startup task which is run after UE4 engine has launched.
  981. function postRunEmscripten() {
  982. taskFinished(TASK_MAIN);
  983. $("#compilingmessage").remove();
  984. // The default Emscripten provided canvas resizing behavior is not needed,
  985. // since we are controlling the canvas sizes here, so stub those functions out.
  986. Browser.updateCanvasDimensions = function() {};
  987. Browser.setCanvasSize = function() {};
  988. // If you'd like to configure the initial canvas size to render using the resolution
  989. // defined in UE4 DefaultEngine.ini [SystemSettings] r.setRes=WidthxHeight,
  990. // uncomment the following two lines before calling resizeCanvas() below:
  991. // canvasAspectRatioWidth = UE_JSlib.UE_GSystemResolution_ResX();
  992. // canvasAspectRatioHeight = UE_JSlib.UE_GSystemResolution_ResY();
  993. // Configure the size of the canvas and display it.
  994. resizeCanvas();
  995. Module['canvas'].style.display = 'block';
  996. // Whenever the browser window size changes, relayout the canvas size on the page.
  997. window.addEventListener('resize', resizeCanvas, false);
  998. window.addEventListener('orientationchange', resizeCanvas, false);
  999. // The following is needed if game is within an iframe - main window already has focus...
  1000. window.focus();
  1001. }
  1002. Module.postRun = [postRunEmscripten];
  1003. // ----------------------------------------
  1004. // ----------------------------------------
  1005. // MAIN
  1006. $(document).ready(function() {
  1007. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1008. // Deduce which version to load up.
  1009. var supportsWasm = (typeof WebAssembly === 'object' && typeof WebAssembly.Memory === 'function');
  1010. if (!supportsWasm) {
  1011. showErrorDialog('Your browser does not support WebAssembly. Please try updating to latest 64-bit browser that supports WebAssembly.<br>Current user agent: ' + navigator.userAgent);
  1012. return;
  1013. }
  1014. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1015. // memory heap
  1016. // if (!Module['buffer']) {
  1017. // showErrorDialog('Failed to allocate ' + MB(MIN_MEMORY) + ' of linear memory for the WebAssembly heap!');
  1018. // return;
  1019. // }
  1020. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1021. // check for webgl and cache it for later (UE_BrowserWebGLVersion() reads this)
  1022. Module['WEBGL_VERSION'] = detectWebGL();
  1023. console.log(getGpuInfo());
  1024. if (!Module['WEBGL_VERSION'] || Module['WEBGL_VERSION'] < requiredWebGLVersion) {
  1025. showErrorDialog('Your browser does not support WebGL ' + requiredWebGLVersion + '<br>Error reason: ' + (Module['webGLErrorReason'] || 'Unknown') + '. Try updating your browser and/or graphics card drivers.<br>Current renderer: ' + getGpuInfo());
  1026. return;
  1027. }
  1028. function shouldBrowserSupportWebGL2() {
  1029. var match = window.navigator.userAgent.match(/Firefox\/([0-9]+)\./);
  1030. if (match) return parseInt(match[1]) >= 51;
  1031. }
  1032. if (Module['WEBGL_VERSION'] < 2 && !explicitlyUseWebGL1) {
  1033. if (shouldBrowserSupportWebGL2()) {
  1034. showWarningRibbon('Your GPU does not support WebGL 2. This affects graphics performance and quality. Please try updating your graphics driver and/or browser to latest version.<br>Error reason: ' + (Module['webGLErrorReason'] || 'Unknown') + '<br>Current renderer: ' + getGpuInfo());
  1035. } else {
  1036. showWarningRibbon('The current browser does not support WebGL 2. This affects graphics performance and quality.<br>Please try updating your browser (and/or video drivers). NOTE: old hardware might have been blacklisted by this browser -- you may need to use a different browser.<br>Error reason: ' + (Module['webGLErrorReason'] || 'Unknown') + '<br>Current renderer: ' + getGpuInfo());
  1037. }
  1038. }
  1039. if (typeof OffscreenCanvas === 'undefined' && targetOffscreenCanvas) {
  1040. showWarningRibbon('This is an experimental UE4 build that uses OffscreenCanvas, but your browser does not seem to support it. Try out Firefox Nightly or Chrome Canary, and in Firefox, set pref gfx.offscreencanvas.enabled;true in about:config, and on Chrome Canary, Enable "Experimental canvas features" in chrome://flags. Continuing without OffscreenCanvas, but performance can be severely affected, and rendering might not look correct.');
  1041. }
  1042. // The following WebGL 1.0 extensions are available in core WebGL 2.0 specification, so they are no longer shown in the extensions list.
  1043. var webGLExtensionsInCoreWebGL2 = ['ANGLE_instanced_arrays','EXT_blend_minmax','EXT_color_buffer_half_float','EXT_frag_depth','EXT_sRGB','EXT_shader_texture_lod','OES_element_index_uint','OES_standard_derivatives','OES_texture_float','OES_texture_half_float','OES_texture_half_float_linear','OES_vertex_array_object','WEBGL_color_buffer_float','WEBGL_depth_texture','WEBGL_draw_buffers'];
  1044. var supportedWebGLExtensions = Module['preinitializedWebGLContext'].getSupportedExtensions();
  1045. if (Module['WEBGL_VERSION'] >= 2) supportedWebGLExtensions = supportedWebGLExtensions.concat(webGLExtensionsInCoreWebGL2);
  1046. // The following WebGL extensions are required by UE4/this project, and it cannot run without.
  1047. var requiredWebGLExtensions = []; // TODO: List WebGL extensions here that the demo needs and can't run without.
  1048. for(var i in requiredWebGLExtensions) {
  1049. if (supportedWebGLExtensions.indexOf(requiredWebGLExtensions[i]) == -1) {
  1050. showErrorDialog('Your browser does not support WebGL extension ' + requiredWebGLExtensions[i] + ', which is required to run this page!');
  1051. }
  1052. }
  1053. // The following WebGL extensions would be preferred to exist for best features/performance, but are not strictly needed and UE4 can fall back if not available.
  1054. var preferredToHaveWebGLExtensions = [// The following are core in WebGL 2:
  1055. 'ANGLE_instanced_arrays', // UE4 uses instanced rendering where possible, but can fallback to noninstanced.
  1056. 'EXT_color_buffer_half_float',
  1057. 'EXT_sRGB',
  1058. 'EXT_shader_texture_lod', // textureLod() is needed for correct reflections, without this reflection shaders are missing and render out black.
  1059. 'OES_standard_derivatives',
  1060. 'OES_texture_half_float',
  1061. 'OES_texture_half_float_linear',
  1062. 'OES_vertex_array_object',
  1063. 'WEBGL_color_buffer_float',
  1064. 'WEBGL_depth_texture',
  1065. 'WEBGL_draw_buffers',
  1066. // These are still extensions in WebGL 2:
  1067. 'OES_texture_float',
  1068. 'WEBGL_compressed_texture_s3tc',
  1069. 'EXT_texture_filter_anisotropic'
  1070. ];
  1071. var unsupportedWebGLExtensions = [];
  1072. for(var i in preferredToHaveWebGLExtensions) {
  1073. if (supportedWebGLExtensions.indexOf(preferredToHaveWebGLExtensions[i]) == -1) {
  1074. unsupportedWebGLExtensions.push(preferredToHaveWebGLExtensions[i]);
  1075. }
  1076. }
  1077. if (unsupportedWebGLExtensions.length > 1) {
  1078. showWarningRibbon('Your browser or graphics card does not support the following WebGL extensions: ' + unsupportedWebGLExtensions.join(', ') + '. This can impact UE4 graphics performance and quality.');
  1079. } else if (unsupportedWebGLExtensions.length == 1) {
  1080. showWarningRibbon('Your browser or graphics card does not support the WebGL extension ' + unsupportedWebGLExtensions[0] + '. This can impact UE4 graphics performance and quality.');
  1081. }
  1082. if (targetOffscreenCanvas) {
  1083. Module['preinitializedWebGLContext'] = null; // TODO: Currently can't preinitialize a context when OffscreenCanvas is used.
  1084. }
  1085. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1086. // browser 64bit vs 32bit check
  1087. if (!heuristicIs64Bit('browser')) {
  1088. if (heuristicIs64Bit('os')) {
  1089. showWarningRibbon('It looks like you are running a 32-bit browser on a 64-bit operating system. This can dramatically affect performance and risk running out of memory on large applications. Try updating to a 64-bit browser for an optimized experience.');
  1090. } else {
  1091. showWarningRibbon('It looks like your computer hardware is 32-bit. This can dramatically affect performance.');
  1092. }
  1093. }
  1094. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1095. // files to download/cache
  1096. function withIndexedDB(db) {
  1097. Module['dbInstance'] = db;
  1098. // ----------------------------------------
  1099. // WASM
  1100. var mainCompiledCode = fetchFromIndexedDB(db, 'wasmModule').then(function(wasmModule) {
  1101. return { db: db, wasmModule: wasmModule, fromIndexedDB: true };
  1102. }).catch(function() {
  1103. return fetchFromIndexedDB(db, 'wasmBytes').then(function(wasmBytes) {
  1104. return { db: db, wasmBytes: wasmBytes, fromIndexedDB: true };
  1105. });
  1106. }).catch(function() {
  1107. return download(Module.locateFile('AHND-HTML5-Shipping.wasm'), 'arraybuffer').then(function(wasmBytes) {
  1108. return { db: db, wasmBytes: wasmBytes, fromIndexedDB: false };
  1109. });
  1110. });
  1111. Module['wasmDownloadAction'] = mainCompiledCode;
  1112. var compiledCodeInstantiateAction = new Promise(function(resolve, reject) {
  1113. Module['wasmInstantiateActionResolve'] = resolve;
  1114. Module['wasmInstantiateActionReject'] = reject;
  1115. });
  1116. // ----------------------------------------
  1117. // MAIN JS
  1118. var mainJsDownload = fetchOrDownloadAndStore(db, Module.locateFile('AHND-HTML5-Shipping.js'), 'blob').then(function(data) {
  1119. Module['mainScriptUrlOrBlob'] = data;
  1120. return addScriptToDom(data).then(function() {
  1121. addRunDependency('wait-for-compiled-code');
  1122. });
  1123. });
  1124. // ----------------------------------------
  1125. // MORE JS
  1126. var dataJsDownload = fetchOrDownloadAndStore(db, Module.locateFile('AHND-HTML5-Shipping.data.js'));
  1127. var utilityJsDownload = fetchOrDownloadAndStore(db, Module.locateFile('Utility.js')).then(addScriptToDom);
  1128. var dataDownload =
  1129. /* // The following code would download and store the .data file as a Blob, which should be more efficient than loading an ArrayBuffer. However that seems to be buggy, so avoid it for now.
  1130. fetchOrDownloadAndStore(db, Module.locateFile('AHND-HTML5-Shipping.data')).then(function(dataBlob) {
  1131. return readBlobToArrayBuffer(dataBlob).then(function(dataArrayBuffer) {
  1132. Module['preloadedPackages'] = {};
  1133. Module['preloadedPackages'][Module.locateFile('AHND-HTML5-Shipping.data')] = dataArrayBuffer;
  1134. return dataJsDownload.then(addScriptToDom);
  1135. })
  1136. });
  1137. */
  1138. // Instead as a fallback, download as ArrayBuffer. (TODO: Figure out the bugs with the above, and switch to using that one instead)
  1139. fetchOrDownloadAndStore(db, Module.locateFile('AHND-HTML5-Shipping.data'), 'arraybuffer').then(function(dataArrayBuffer) {
  1140. Module['preloadedPackages'] = {};
  1141. Module['preloadedPackages'][Module.locateFile('AHND-HTML5-Shipping.data')] = dataArrayBuffer;
  1142. return dataJsDownload.then(addScriptToDom);
  1143. });
  1144. // ----------------------------------------
  1145. // SHADERS
  1146. const precompileShaders = false; // Currently not enabled.
  1147. if (precompileShaders) {
  1148. var compileShaders = fetchOrDownloadAndStore(db, Module.locateFile('shaders.json'), 'arraybuffer')
  1149. .then(function(json) {
  1150. return compileShadersFromJson(json)
  1151. .catch(function(error) {
  1152. taskFinished(TASK_SHADERS, error + '<br>Current renderer: ' + getGpuInfo());
  1153. throw 'Shader compilation failed';
  1154. });
  1155. });
  1156. } else {
  1157. var compileShaders = true; // Not precompiling shaders, no-op Promise action.
  1158. }
  1159. // ----------------------------------------
  1160. // WAIT FOR DOWNLOADS AND COMPILES
  1161. Promise.all([mainCompiledCode, mainJsDownload, utilityJsDownload, dataDownload, compiledCodeInstantiateAction, compileShaders]).then(function() {
  1162. if (!precompileShaders) {
  1163. Module['precompiledShaders'] = Module['precompiledPrograms'] = Module['preinitializedWebGLContext'] = Module['glIDCounter'] = Module['precompiledUniforms'] = null;
  1164. }
  1165. taskProgress(TASK_MAIN);
  1166. removeRunDependency('wait-for-compiled-code'); // Now we are ready to call main()
  1167. });
  1168. };
  1169. // ----------------------------------------
  1170. // GO !
  1171. openIndexedDB(Module['UE4_indexedDBName'], Module['UE4_indexedDBVersion'] || 1).then(withIndexedDB).catch(function(e) {
  1172. if ( enableReadFromIndexedDB || enableWriteToIndexedDB ) {
  1173. console.error('Failed to openIndexedDB, proceeding without reading or storing contents to IndexedDB! Error: ');
  1174. }
  1175. console.error(e);
  1176. withIndexedDB(null);
  1177. });
  1178. });