cm107 commited on
Commit
8c33d0f
1 Parent(s): 7f8a074

Initial commit

Browse files
.gitattributes CHANGED
@@ -32,3 +32,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
32
  *.zip filter=lfs diff=lfs merge=lfs -text
33
  *.zst filter=lfs diff=lfs merge=lfs -text
34
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
32
  *.zip filter=lfs diff=lfs merge=lfs -text
33
  *.zst filter=lfs diff=lfs merge=lfs -text
34
  *tfevents* filter=lfs diff=lfs merge=lfs -text
35
+ *.data filter=lfs diff=lfs merge=lfs -text
Build/SimplifiedTerrain-simpleMovement-light-demo-webgl-dev.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1cc92c0be5a1574d80ca2f5e1ef89f8a5ae2abcd45d9dba478c40283215eac9c
3
+ size 125764842
Build/SimplifiedTerrain-simpleMovement-light-demo-webgl-dev.framework.js ADDED
The diff for this file is too large to render. See raw diff
 
Build/SimplifiedTerrain-simpleMovement-light-demo-webgl-dev.loader.js ADDED
@@ -0,0 +1,1238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ function createUnityInstance(canvas, config, onProgress) {
2
+ onProgress = onProgress || function () {};
3
+
4
+
5
+ function showBanner(msg, type) {
6
+ // Only ever show one error at most - other banner messages after that should get ignored
7
+ // to avoid noise.
8
+ if (!showBanner.aborted && config.showBanner) {
9
+ if (type == 'error') showBanner.aborted = true;
10
+ return config.showBanner(msg, type);
11
+ }
12
+
13
+ // Fallback to console logging if visible banners have been suppressed
14
+ // from the main page.
15
+ switch(type) {
16
+ case 'error': console.error(msg); break;
17
+ case 'warning': console.warn(msg); break;
18
+ default: console.log(msg); break;
19
+ }
20
+ }
21
+
22
+ function errorListener(e) {
23
+ var error = e.reason || e.error;
24
+ var message = error ? error.toString() : (e.message || e.reason || '');
25
+ var stack = (error && error.stack) ? error.stack.toString() : '';
26
+
27
+ // Do not repeat the error message if it's present in the stack trace.
28
+ if (stack.startsWith(message)) {
29
+ stack = stack.substring(message.length);
30
+ }
31
+
32
+ message += '\n' + stack.trim();
33
+
34
+ if (!message || !Module.stackTraceRegExp || !Module.stackTraceRegExp.test(message))
35
+ return;
36
+
37
+ var filename = e.filename || (error && (error.fileName || error.sourceURL)) || '';
38
+ var lineno = e.lineno || (error && (error.lineNumber || error.line)) || 0;
39
+
40
+ errorHandler(message, filename, lineno);
41
+ }
42
+
43
+ var Module = {
44
+ canvas: canvas,
45
+ webglContextAttributes: {
46
+ preserveDrawingBuffer: false,
47
+ },
48
+ cacheControl: function (url) {
49
+ return (url == Module.dataUrl || url.match(/\.bundle/)) ? "must-revalidate" : "no-store";
50
+ },
51
+ streamingAssetsUrl: "StreamingAssets",
52
+ downloadProgress: {},
53
+ deinitializers: [],
54
+ intervals: {},
55
+ setInterval: function (func, ms) {
56
+ var id = window.setInterval(func, ms);
57
+ this.intervals[id] = true;
58
+ return id;
59
+ },
60
+ clearInterval: function(id) {
61
+ delete this.intervals[id];
62
+ window.clearInterval(id);
63
+ },
64
+ preRun: [],
65
+ postRun: [],
66
+ print: function (message) {
67
+ console.log(message);
68
+ },
69
+ printErr: function (message) {
70
+ console.error(message);
71
+
72
+ if (typeof message === 'string' && message.indexOf('wasm streaming compile failed') != -1) {
73
+ if (message.toLowerCase().indexOf('mime') != -1) {
74
+ showBanner('HTTP Response Header "Content-Type" configured incorrectly on the server for file ' + Module.codeUrl + ' , should be "application/wasm". Startup time performance will suffer.', 'warning');
75
+ } else {
76
+ showBanner('WebAssembly streaming compilation failed! This can happen for example if "Content-Encoding" HTTP header is incorrectly enabled on the server for file ' + Module.codeUrl + ', but the file is not pre-compressed on disk (or vice versa). Check the Network tab in browser Devtools to debug server header configuration.', 'warning');
77
+ }
78
+ }
79
+ },
80
+ locateFile: function (url) {
81
+ return (
82
+ url == "build.wasm" ? this.codeUrl :
83
+ url
84
+ );
85
+ },
86
+ disabledCanvasEvents: [
87
+ "contextmenu",
88
+ "dragstart",
89
+ ],
90
+ };
91
+
92
+ for (var parameter in config)
93
+ Module[parameter] = config[parameter];
94
+
95
+ Module.streamingAssetsUrl = new URL(Module.streamingAssetsUrl, document.URL).href;
96
+
97
+ // Operate on a clone of Module.disabledCanvasEvents field so that at Quit time
98
+ // we will ensure we'll remove the events that we created (in case user has
99
+ // modified/cleared Module.disabledCanvasEvents in between)
100
+ var disabledCanvasEvents = Module.disabledCanvasEvents.slice();
101
+
102
+ function preventDefault(e) {
103
+ e.preventDefault();
104
+ }
105
+
106
+ disabledCanvasEvents.forEach(function (disabledCanvasEvent) {
107
+ canvas.addEventListener(disabledCanvasEvent, preventDefault);
108
+ });
109
+
110
+ window.addEventListener("error", errorListener);
111
+ window.addEventListener("unhandledrejection", errorListener);
112
+
113
+ // Safari does not automatically stretch the fullscreen element to fill the screen.
114
+ // The CSS width/height of the canvas causes it to remain the same size in the full screen
115
+ // window on Safari, resulting in it being a small canvas with black borders filling the
116
+ // rest of the screen.
117
+ var _savedElementWidth = "";
118
+ var _savedElementHeight = "";
119
+ // Safari uses webkitfullscreenchange event and not fullscreenchange
120
+ document.addEventListener("webkitfullscreenchange", function(e) {
121
+ // Safari uses webkitCurrentFullScreenElement and not fullscreenElement.
122
+ var fullscreenElement = document.webkitCurrentFullScreenElement;
123
+ if (fullscreenElement === canvas) {
124
+ if (canvas.style.width) {
125
+ _savedElementWidth = canvas.style.width;
126
+ _savedElementHeight = canvas.style.height;
127
+ canvas.style.width = "100%";
128
+ canvas.style.height = "100%";
129
+ }
130
+ } else {
131
+ if (_savedElementWidth) {
132
+ canvas.style.width = _savedElementWidth;
133
+ canvas.style.height = _savedElementHeight;
134
+ _savedElementWidth = "";
135
+ _savedElementHeight = "";
136
+ }
137
+ }
138
+ });
139
+
140
+ // Clear the event handlers we added above when the app quits, so that the event handler
141
+ // functions will not hold references to this JS function scope after
142
+ // exit, to allow JS garbage collection to take place.
143
+ Module.deinitializers.push(function() {
144
+ Module['disableAccessToMediaDevices']();
145
+ disabledCanvasEvents.forEach(function (disabledCanvasEvent) {
146
+ canvas.removeEventListener(disabledCanvasEvent, preventDefault);
147
+ });
148
+ window.removeEventListener("error", errorListener);
149
+ window.removeEventListener("unhandledrejection", errorListener);
150
+
151
+ for (var id in Module.intervals)
152
+ {
153
+ window.clearInterval(id);
154
+ }
155
+ Module.intervals = {};
156
+ });
157
+
158
+ Module.QuitCleanup = function () {
159
+ for (var i = 0; i < Module.deinitializers.length; i++) {
160
+ Module.deinitializers[i]();
161
+ }
162
+ Module.deinitializers = [];
163
+ // After all deinitializer callbacks are called, notify user code that the Unity game instance has now shut down.
164
+ if (typeof Module.onQuit == "function")
165
+ Module.onQuit();
166
+
167
+ };
168
+
169
+ var unityInstance = {
170
+ Module: Module,
171
+ SetFullscreen: function () {
172
+ if (Module.SetFullscreen)
173
+ return Module.SetFullscreen.apply(Module, arguments);
174
+ Module.print("Failed to set Fullscreen mode: Player not loaded yet.");
175
+ },
176
+ SendMessage: function () {
177
+ if (Module.SendMessage)
178
+ return Module.SendMessage.apply(Module, arguments);
179
+ Module.print("Failed to execute SendMessage: Player not loaded yet.");
180
+ },
181
+ Quit: function () {
182
+ return new Promise(function (resolve, reject) {
183
+ Module.shouldQuit = true;
184
+ Module.onQuit = resolve;
185
+ });
186
+ },
187
+ };
188
+
189
+
190
+ Module.SystemInfo = (function () {
191
+
192
+ var browser, browserVersion, os, osVersion, canvas, gpu;
193
+
194
+ var ua = navigator.userAgent + ' ';
195
+ var browsers = [
196
+ ['Firefox', 'Firefox'],
197
+ ['OPR', 'Opera'],
198
+ ['Edg', 'Edge'],
199
+ ['SamsungBrowser', 'Samsung Browser'],
200
+ ['Trident', 'Internet Explorer'],
201
+ ['MSIE', 'Internet Explorer'],
202
+ ['Chrome', 'Chrome'],
203
+ ['CriOS', 'Chrome on iOS Safari'],
204
+ ['FxiOS', 'Firefox on iOS Safari'],
205
+ ['Safari', 'Safari'],
206
+ ];
207
+
208
+ function extractRe(re, str, idx) {
209
+ re = RegExp(re, 'i').exec(str);
210
+ return re && re[idx];
211
+ }
212
+ for(var b = 0; b < browsers.length; ++b) {
213
+ browserVersion = extractRe(browsers[b][0] + '[\/ ](.*?)[ \\)]', ua, 1);
214
+ if (browserVersion) {
215
+ browser = browsers[b][1];
216
+ break;
217
+ }
218
+ }
219
+ if (browser == 'Safari') browserVersion = extractRe('Version\/(.*?) ', ua, 1);
220
+ if (browser == 'Internet Explorer') browserVersion = extractRe('rv:(.*?)\\)? ', ua, 1) || browserVersion;
221
+
222
+ // These OS strings need to match the ones in Runtime/Misc/SystemInfo.cpp::GetOperatingSystemFamily()
223
+ var oses = [
224
+ ['Windows (.*?)[;\)]', 'Windows'],
225
+ ['Android ([0-9_\.]+)', 'Android'],
226
+ ['iPhone OS ([0-9_\.]+)', 'iPhoneOS'],
227
+ ['iPad.*? OS ([0-9_\.]+)', 'iPadOS'],
228
+ ['FreeBSD( )', 'FreeBSD'],
229
+ ['OpenBSD( )', 'OpenBSD'],
230
+ ['Linux|X11()', 'Linux'],
231
+ ['Mac OS X ([0-9_\.]+)', 'MacOS'],
232
+ ['bot|google|baidu|bing|msn|teoma|slurp|yandex', 'Search Bot']
233
+ ];
234
+ for(var o = 0; o < oses.length; ++o) {
235
+ osVersion = extractRe(oses[o][0], ua, 1);
236
+ if (osVersion) {
237
+ os = oses[o][1];
238
+ osVersion = osVersion.replace(/_/g, '.');
239
+ break;
240
+ }
241
+ }
242
+ var versionMappings = {
243
+ 'NT 5.0': '2000',
244
+ 'NT 5.1': 'XP',
245
+ 'NT 5.2': 'Server 2003',
246
+ 'NT 6.0': 'Vista',
247
+ 'NT 6.1': '7',
248
+ 'NT 6.2': '8',
249
+ 'NT 6.3': '8.1',
250
+ 'NT 10.0': '10'
251
+ };
252
+ osVersion = versionMappings[osVersion] || osVersion;
253
+
254
+ // TODO: Add mobile device identifier, e.g. SM-G960U
255
+
256
+ canvas = document.createElement("canvas");
257
+ if (canvas) {
258
+ gl = canvas.getContext("webgl2");
259
+ glVersion = gl ? 2 : 0;
260
+ if (!gl) {
261
+ if (gl = canvas && canvas.getContext("webgl")) glVersion = 1;
262
+ }
263
+
264
+ if (gl) {
265
+ gpu = (gl.getExtension("WEBGL_debug_renderer_info") && gl.getParameter(0x9246 /*debugRendererInfo.UNMASKED_RENDERER_WEBGL*/)) || gl.getParameter(0x1F01 /*gl.RENDERER*/);
266
+ }
267
+ }
268
+
269
+ var hasThreads = typeof SharedArrayBuffer !== 'undefined';
270
+ var hasWasm = typeof WebAssembly === "object" && typeof WebAssembly.compile === "function";
271
+ return {
272
+ width: screen.width,
273
+ height: screen.height,
274
+ userAgent: ua.trim(),
275
+ browser: browser || 'Unknown browser',
276
+ browserVersion: browserVersion || 'Unknown version',
277
+ mobile: /Mobile|Android|iP(ad|hone)/.test(navigator.appVersion),
278
+ os: os || 'Unknown OS',
279
+ osVersion: osVersion || 'Unknown OS Version',
280
+ gpu: gpu || 'Unknown GPU',
281
+ language: navigator.userLanguage || navigator.language,
282
+ hasWebGL: glVersion,
283
+ hasCursorLock: !!document.body.requestPointerLock,
284
+ hasFullscreen: !!document.body.requestFullscreen || !!document.body.webkitRequestFullscreen, // Safari still uses the webkit prefixed version
285
+ hasThreads: hasThreads,
286
+ hasWasm: hasWasm,
287
+ // This should be updated when we re-enable wasm threads. Previously it checked for WASM thread
288
+ // support with: var wasmMemory = hasWasm && hasThreads && new WebAssembly.Memory({"initial": 1, "maximum": 1, "shared": true});
289
+ // which caused Chrome to have a warning that SharedArrayBuffer requires cross origin isolation.
290
+ hasWasmThreads: false,
291
+ };
292
+ })();
293
+
294
+ function errorHandler(message, filename, lineno) {
295
+ // Unity needs to rely on Emscripten deferred fullscreen requests, so these will make their way to error handler
296
+ if (message.indexOf('fullscreen error') != -1)
297
+ return;
298
+
299
+ if (Module.startupErrorHandler) {
300
+ Module.startupErrorHandler(message, filename, lineno);
301
+ return;
302
+ }
303
+ if (Module.errorHandler && Module.errorHandler(message, filename, lineno))
304
+ return;
305
+ console.log("Invoking error handler due to\n" + message);
306
+
307
+ // Support Firefox window.dump functionality.
308
+ if (typeof dump == "function")
309
+ dump("Invoking error handler due to\n" + message);
310
+
311
+ if (errorHandler.didShowErrorMessage)
312
+ return;
313
+ var message = "An error occurred running the Unity content on this page. See your browser JavaScript console for more info. The error was:\n" + message;
314
+ if (message.indexOf("DISABLE_EXCEPTION_CATCHING") != -1) {
315
+ message = "An exception has occurred, but exception handling has been disabled in this build. If you are the developer of this content, enable exceptions in your project WebGL player settings to be able to catch the exception or see the stack trace.";
316
+ } else if (message.indexOf("Cannot enlarge memory arrays") != -1) {
317
+ message = "Out of memory. If you are the developer of this content, try allocating more memory to your WebGL build in the WebGL player settings.";
318
+ } else if (message.indexOf("Invalid array buffer length") != -1 || message.indexOf("Invalid typed array length") != -1 || message.indexOf("out of memory") != -1 || message.indexOf("could not allocate memory") != -1) {
319
+ message = "The browser could not allocate enough memory for the WebGL content. If you are the developer of this content, try allocating less memory to your WebGL build in the WebGL player settings.";
320
+ }
321
+ alert(message);
322
+ errorHandler.didShowErrorMessage = true;
323
+ }
324
+
325
+
326
+ Module.abortHandler = function (message) {
327
+ errorHandler(message, "", 0);
328
+ return true;
329
+ };
330
+
331
+ Error.stackTraceLimit = Math.max(Error.stackTraceLimit || 0, 50);
332
+
333
+ function progressUpdate(id, e) {
334
+ if (id == "symbolsUrl")
335
+ return;
336
+ var progress = Module.downloadProgress[id];
337
+ if (!progress)
338
+ progress = Module.downloadProgress[id] = {
339
+ started: false,
340
+ finished: false,
341
+ lengthComputable: false,
342
+ total: 0,
343
+ loaded: 0,
344
+ };
345
+ if (typeof e == "object" && (e.type == "progress" || e.type == "load")) {
346
+ if (!progress.started) {
347
+ progress.started = true;
348
+ progress.lengthComputable = e.lengthComputable;
349
+ }
350
+ progress.total = e.total;
351
+ progress.loaded = e.loaded;
352
+ if (e.type == "load")
353
+ progress.finished = true;
354
+ }
355
+ var loaded = 0, total = 0, started = 0, computable = 0, unfinishedNonComputable = 0;
356
+ for (var id in Module.downloadProgress) {
357
+ var progress = Module.downloadProgress[id];
358
+ if (!progress.started)
359
+ return 0;
360
+ started++;
361
+ if (progress.lengthComputable) {
362
+ loaded += progress.loaded;
363
+ total += progress.total;
364
+ computable++;
365
+ } else if (!progress.finished) {
366
+ unfinishedNonComputable++;
367
+ }
368
+ }
369
+ var totalProgress = started ? (started - unfinishedNonComputable - (total ? computable * (total - loaded) / total : 0)) / started : 0;
370
+ onProgress(0.9 * totalProgress);
371
+ }
372
+
373
+ Module.readBodyWithProgress = function() {
374
+ /**
375
+ * Estimate length of uncompressed content by taking average compression ratios
376
+ * of compression type into account.
377
+ * @param {Response} response A Fetch API response object
378
+ * @param {boolean} lengthComputable Return wether content length was given in header.
379
+ * @returns {number}
380
+ */
381
+ function estimateContentLength(response, lengthComputable) {
382
+ if (!lengthComputable) {
383
+ // No content length available
384
+ return 0;
385
+ }
386
+
387
+ var compression = response.headers.get("Content-Encoding");
388
+ var contentLength = parseInt(response.headers.get("Content-Length"));
389
+
390
+ switch (compression) {
391
+ case "br":
392
+ return Math.round(contentLength * 5);
393
+ case "gzip":
394
+ return Math.round(contentLength * 4);
395
+ default:
396
+ return contentLength;
397
+ }
398
+ }
399
+
400
+ function readBodyWithProgress(response, onProgress) {
401
+ var reader = response.body ? response.body.getReader() : undefined;
402
+ var lengthComputable = typeof response.headers.get('Content-Length') !== "undefined";
403
+ var estimatedContentLength = estimateContentLength(response, lengthComputable);
404
+ var body = new Uint8Array(estimatedContentLength);
405
+ var trailingChunks = [];
406
+ var receivedLength = 0;
407
+ var trailingChunksStart = 0;
408
+
409
+ if (!lengthComputable) {
410
+ console.warn("[UnityCache] Response is served without Content-Length header. Please reconfigure server to include valid Content-Length for better download performance.");
411
+ }
412
+
413
+ function readBody() {
414
+ if (typeof reader === "undefined") {
415
+ // Browser does not support streaming reader API
416
+ // Fallback to Respone.arrayBuffer()
417
+ return response.arrayBuffer().then(function (buffer) {
418
+ onProgress({
419
+ type: "progress",
420
+ total: buffer.length,
421
+ loaded: 0,
422
+ lengthComputable: lengthComputable
423
+ });
424
+
425
+ return new Uint8Array(buffer);
426
+ });
427
+ }
428
+
429
+ // Start reading memory chunks
430
+ return reader.read().then(function (result) {
431
+ if (result.done) {
432
+ return concatenateTrailingChunks();
433
+ }
434
+
435
+ if ((receivedLength + result.value.length) <= body.length) {
436
+ // Directly append chunk to body if enough memory was allocated
437
+ body.set(result.value, receivedLength);
438
+ trailingChunksStart = receivedLength + result.value.length;
439
+ } else {
440
+ // Store additional chunks in array to append later
441
+ trailingChunks.push(result.value);
442
+ }
443
+
444
+ receivedLength += result.value.length;
445
+ onProgress({
446
+ type: "progress",
447
+ total: Math.max(estimatedContentLength, receivedLength),
448
+ loaded: receivedLength,
449
+ lengthComputable: lengthComputable
450
+ });
451
+
452
+ return readBody();
453
+ });
454
+ }
455
+
456
+ function concatenateTrailingChunks() {
457
+ if (receivedLength === estimatedContentLength) {
458
+ return body;
459
+ }
460
+
461
+ if (receivedLength < estimatedContentLength) {
462
+ // Less data received than estimated, shrink body
463
+ return body.slice(0, receivedLength);
464
+ }
465
+
466
+ // More data received than estimated, create new larger body to prepend all additional chunks to the body
467
+ var newBody = new Uint8Array(receivedLength);
468
+ newBody.set(body, 0);
469
+ var position = trailingChunksStart;
470
+ for (var i = 0; i < trailingChunks.length; ++i) {
471
+ newBody.set(trailingChunks[i], position);
472
+ position += trailingChunks[i].length;
473
+ }
474
+
475
+ return newBody;
476
+ }
477
+
478
+ return readBody().then(function (parsedBody) {
479
+ onProgress({
480
+ type: "load",
481
+ total: parsedBody.length,
482
+ loaded: parsedBody.length,
483
+ lengthComputable: lengthComputable
484
+ });
485
+
486
+ response.parsedBody = parsedBody;
487
+ return response;
488
+ });
489
+ }
490
+
491
+ return readBodyWithProgress;
492
+ }();
493
+
494
+ Module.fetchWithProgress = function () {
495
+ function fetchWithProgress(resource, init) {
496
+ var onProgress = function () { };
497
+ if (init && init.onProgress) {
498
+ onProgress = init.onProgress;
499
+ }
500
+
501
+ return fetch(resource, init).then(function (response) {
502
+ return Module.readBodyWithProgress(response, onProgress);
503
+ });
504
+ }
505
+
506
+ return fetchWithProgress;
507
+ }();
508
+ /**
509
+ * @interface RequestMetaData
510
+ * An object with meta data for a request
511
+ *
512
+ * @property {string} url The url of a request
513
+ * @property {string} company The company name
514
+ * @property {string} product The product name
515
+ * @property {number} version The version of the build
516
+ * @property {number} size The company of the build
517
+ * @property {number} accessedAt Timestamp when request was last accessed (Unix timestamp format)
518
+ * @property {number} updatedAt Timestamp when request was last updated in the cache (Unix timestamp format)
519
+ */
520
+
521
+ /**
522
+ * @interface ResponseWithMetaData
523
+ * An object with a cached response and meta data
524
+ * @property {Response} response
525
+ * @property {RequestMetaData} metaData
526
+ */
527
+
528
+ Module.UnityCache = function () {
529
+ var UnityCacheDatabase = { name: "UnityCache", version: 4 };
530
+ var RequestMetaDataStore = { name: "RequestMetaDataStore", version: 1 };
531
+ var RequestStore = { name: "RequestStore", version: 1 };
532
+ var WebAssemblyStore = { name: "WebAssembly", version: 1 };
533
+ var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
534
+
535
+ function log(message) {
536
+ console.log("[UnityCache] " + message);
537
+ }
538
+
539
+ /**
540
+ * A request cache that uses the browser Index DB to cache large requests
541
+ * @property {Promise<void>} isConnected
542
+ * @property {Cache} cache
543
+ */
544
+ function UnityCache() {
545
+ var self = this;
546
+
547
+ this.isConnected = this.connect().then(function () {
548
+ return self.cleanUpCache();
549
+ });
550
+
551
+ this.isConnected.catch(function (error) {
552
+ log("Error when initializing cache: " + error);
553
+ });
554
+ }
555
+
556
+ var instance = null;
557
+ /**
558
+ * Singleton accessor. Returns unity cache instance
559
+ * @returns {UnityCache}
560
+ */
561
+ UnityCache.getInstance = function () {
562
+ if (!instance) {
563
+ instance = new UnityCache();
564
+ }
565
+
566
+ return instance;
567
+ }
568
+
569
+ /**
570
+ * Destroy unity cache instance. Returns a promise that waits for the
571
+ * database connection to be closed.
572
+ * @returns {Promise<void>}
573
+ */
574
+ UnityCache.destroyInstance = function () {
575
+ if (!instance) {
576
+ return Promise.resolve();
577
+ }
578
+
579
+ return instance.close().then(function () {
580
+ instance = null;
581
+ });
582
+ }
583
+
584
+ /**
585
+ * Clear the unity cache.
586
+ * @returns {Promise<void>} A promise that resolves when the cache is cleared.
587
+ */
588
+ UnityCache.prototype.clearCache = function () {
589
+ var self = this;
590
+
591
+ function deleteCacheEntries(cacheKeys) {
592
+ if (cacheKeys.length === 0) {
593
+ return Promise.resolve();
594
+ }
595
+
596
+ var key = cacheKeys.pop();
597
+
598
+ return self.cache.delete(key).then(function () {
599
+ return deleteCacheEntries(cacheKeys);
600
+ });
601
+ }
602
+
603
+ return this.isConnected.then(function () {
604
+ return self.execute(RequestMetaDataStore.name, "clear", []);
605
+ }).then(function () {
606
+ return self.cache.keys();
607
+ }).then(function (keys) {
608
+ return deleteCacheEntries(keys)
609
+ });
610
+ }
611
+
612
+ /**
613
+ * Config for request meta data store
614
+ */
615
+ UnityCache.UnityCacheDatabase = UnityCacheDatabase;
616
+ UnityCache.RequestMetaDataStore = RequestMetaDataStore;
617
+ UnityCache.MaximumCacheSize = 1024 * 1024 * 1024; // 1 GB
618
+
619
+ /**
620
+ * Load a request response from cache
621
+ * @param {Request|string} request The fetch request
622
+ * @returns {Promise<ResponseWithMetaData|undefined>} A cached response with meta data for the request or undefined if request is not in cache.
623
+ */
624
+ UnityCache.prototype.loadRequest = function (request) {
625
+ var self = this;
626
+
627
+ return self.isConnected.then(function () {
628
+ return Promise.all([
629
+ self.cache.match(request),
630
+ self.loadRequestMetaData(request)
631
+ ]);
632
+ }).then(function (result) {
633
+ if (typeof result[0] === "undefined" || typeof result[1] === "undefined") {
634
+ return undefined;
635
+ }
636
+
637
+ return {
638
+ response: result[0],
639
+ metaData: result[1]
640
+ };
641
+ });
642
+ }
643
+
644
+ /**
645
+ * Load a request meta data from cache
646
+ * @param {Request|string} request The fetch request
647
+ * @returns {Promise<RequestMetaData>} Request meta data
648
+ */
649
+ UnityCache.prototype.loadRequestMetaData = function (request) {
650
+ var url = typeof request === "string" ? request : request.url;
651
+
652
+ return this.execute(RequestMetaDataStore.name, "get", [url]);
653
+ }
654
+
655
+ /**
656
+ * Update meta data of a request
657
+ * @param {RequestMetaData} metaData
658
+ * @returns {Promise<void>}
659
+ */
660
+ UnityCache.prototype.updateRequestMetaData = function (metaData) {
661
+ return this.execute(RequestMetaDataStore.name, "put", [metaData]);
662
+ }
663
+
664
+ /**
665
+ * Store request in cache
666
+ * @param {Request} request
667
+ * @param {Response} response
668
+ * @returns {Promise<void>}
669
+ */
670
+ UnityCache.prototype.storeRequest = function (request, response) {
671
+ var self = this;
672
+
673
+ return self.isConnected.then(function () {
674
+ return self.cache.put(request, response);
675
+ });
676
+ }
677
+
678
+ /**
679
+ * Close database and cache connection.
680
+ * @async
681
+ */
682
+ UnityCache.prototype.close = function () {
683
+ return this.isConnected.then(function () {
684
+ if (this.database) {
685
+ this.database.close();
686
+ this.database = null;
687
+ }
688
+
689
+ if (this.cache) {
690
+ this.cache = null;
691
+ }
692
+
693
+ }.bind(this));
694
+ }
695
+
696
+
697
+ /**
698
+ * Create a connection to Cache and IndexedDB for meta data storage
699
+ * @private
700
+ * @async
701
+ * @returns {Promise<void>} A Promise that is resolved when a connection to the IndexedDB and cache are established.
702
+ */
703
+ UnityCache.prototype.connect = function () {
704
+ var self = this;
705
+
706
+ if (typeof indexedDB === "undefined") {
707
+ return Promise.reject(new Error("Could not connect to cache: IndexedDB is not supported."));
708
+ }
709
+
710
+ if (typeof window.caches === "undefined") {
711
+ return Promise.reject(new Error("Could not connect to cache: Cache API is not supported."));
712
+ }
713
+
714
+ var isConnected = new Promise(function (resolve, reject) {
715
+ try {
716
+ // Workaround for WebKit bug 226547:
717
+ // On very first page load opening a connection to IndexedDB hangs without triggering onerror.
718
+ // Add a timeout that triggers the error handling code.
719
+ self.openDBTimeout = setTimeout(function () {
720
+ if (typeof self.database != "undefined") {
721
+ return;
722
+ }
723
+
724
+ reject(new Error("Could not connect to cache: Database timeout."));
725
+ }, 20000);
726
+
727
+ function clearOpenDBTimeout() {
728
+ if (!self.openDBTimeout) {
729
+ return;
730
+ }
731
+
732
+ clearTimeout(self.openDBTimeout);
733
+ self.openDBTimeout = null;
734
+ }
735
+
736
+ var openRequest = indexedDB.open(UnityCacheDatabase.name, UnityCacheDatabase.version);
737
+
738
+ openRequest.onupgradeneeded = self.upgradeDatabase.bind(self);
739
+
740
+ openRequest.onsuccess = function (e) {
741
+ clearOpenDBTimeout();
742
+ self.database = e.target.result;
743
+ resolve();
744
+ };
745
+
746
+ openRequest.onerror = function (error) {
747
+ clearOpenDBTimeout();
748
+ self.database = null;
749
+ reject(new Error("Could not connect to database."));
750
+ };
751
+ } catch (error) {
752
+ clearOpenDBTimeout();
753
+ self.database = null;
754
+ self.cache = null;
755
+ reject(new Error("Could not connect to cache: Could not connect to database."));
756
+ }
757
+ }).then(function () {
758
+ var cacheName = UnityCacheDatabase.name + "_" + Module.companyName + "_" + Module.productName;
759
+
760
+ return caches.open(cacheName);
761
+ }).then(function (cache) {
762
+ self.cache = cache;
763
+ });
764
+
765
+ return isConnected;
766
+ }
767
+
768
+ /**
769
+ * Upgrade object store if database is outdated
770
+ * @private
771
+ * @param {any} e Database upgrade event
772
+ */
773
+ UnityCache.prototype.upgradeDatabase = function (e) {
774
+ var database = e.target.result;
775
+
776
+ if (!database.objectStoreNames.contains(RequestMetaDataStore.name)) {
777
+ var objectStore = database.createObjectStore(RequestMetaDataStore.name, { keyPath: "url" });
778
+ ["accessedAt", "updatedAt"].forEach(function (index) { objectStore.createIndex(index, index); });
779
+ }
780
+
781
+ if (database.objectStoreNames.contains(RequestStore.name)) {
782
+ database.deleteObjectStore(RequestStore.name);
783
+ }
784
+
785
+ if (database.objectStoreNames.contains(WebAssemblyStore.name)) {
786
+ database.deleteObjectStore(WebAssemblyStore.name);
787
+ }
788
+ }
789
+
790
+ /**
791
+ * Execute an operation on the cache
792
+ * @private
793
+ * @param {string} store The name of the store to use
794
+ * @param {string} operation The operation to to execute on the cache
795
+ * @param {Array} parameters Parameters for the operation
796
+ * @returns {Promise} A promise to the cache entry
797
+ */
798
+ UnityCache.prototype.execute = function (store, operation, parameters) {
799
+ return this.isConnected.then(function () {
800
+ return new Promise(function (resolve, reject) {
801
+ try {
802
+ // Failure during initialization of database -> reject Promise
803
+ if (this.database === null) {
804
+ reject(new Error("indexedDB access denied"))
805
+ return;
806
+ }
807
+
808
+ // Create a transaction for the request
809
+ var accessMode = ["put", "delete", "clear"].indexOf(operation) != -1 ? "readwrite" : "readonly";
810
+ var transaction = this.database.transaction([store], accessMode)
811
+ var target = transaction.objectStore(store);
812
+ if (operation == "openKeyCursor") {
813
+ target = target.index(parameters[0]);
814
+ parameters = parameters.slice(1);
815
+ }
816
+
817
+ // Make a request to the database
818
+ var request = target[operation].apply(target, parameters);
819
+ request.onsuccess = function (e) {
820
+ resolve(e.target.result);
821
+ };
822
+ request.onerror = function (error) {
823
+ reject(error);
824
+ };
825
+ } catch (error) {
826
+ reject(error);
827
+ }
828
+ }.bind(this));
829
+ }.bind(this));
830
+ }
831
+
832
+ UnityCache.prototype.getMetaDataEntries = function () {
833
+ var self = this;
834
+ var cacheSize = 0;
835
+ var metaDataEntries = [];
836
+
837
+ return new Promise(function (resolve, reject) {
838
+ var transaction = self.database.transaction([RequestMetaDataStore.name], "readonly");
839
+ var target = transaction.objectStore(RequestMetaDataStore.name);
840
+ var request = target.openCursor();
841
+
842
+ request.onsuccess = function (event) {
843
+ var cursor = event.target.result;
844
+
845
+ if (cursor) {
846
+ cacheSize += cursor.value.size;
847
+ metaDataEntries.push(cursor.value);
848
+
849
+ cursor.continue();
850
+ } else {
851
+ resolve({
852
+ metaDataEntries: metaDataEntries,
853
+ cacheSize: cacheSize
854
+ });
855
+ }
856
+ };
857
+ request.onerror = function (error) {
858
+ reject(error);
859
+ };
860
+ });
861
+ }
862
+
863
+ /**
864
+ * Clean up cache by removing outdated entries.
865
+ * @private
866
+ * @returns {Promise<void>}
867
+ */
868
+ UnityCache.prototype.cleanUpCache = function () {
869
+ var self = this;
870
+
871
+ return this.getMetaDataEntries().then(function (result) {
872
+ var metaDataEntries = result.metaDataEntries;
873
+ var cacheSize = result.cacheSize;
874
+ var entriesToDelete = [];
875
+ var newMetaDataEntries = [];
876
+
877
+ // Remove cached entries with outdated product version
878
+ for (var i = 0; i < metaDataEntries.length; ++i) {
879
+ if (metaDataEntries[i].version == Module.productVersion) {
880
+ newMetaDataEntries.push(metaDataEntries[i]);
881
+ continue;
882
+ }
883
+
884
+ entriesToDelete.push(metaDataEntries[i]);
885
+ cacheSize -= metaDataEntries[i].size;
886
+ }
887
+
888
+ // Remove cache entries until cache size limit is met
889
+ newMetaDataEntries.sort(function (a,b) {
890
+ return a.accessedAt - b.accessedAt;
891
+ });
892
+
893
+ for (var i = 0; i < newMetaDataEntries.length; ++i) {
894
+ if (cacheSize < UnityCache.MaximumCacheSize) {
895
+ break;
896
+ }
897
+
898
+ entriesToDelete.push(newMetaDataEntries[i]);
899
+ cacheSize -= newMetaDataEntries[i].size;
900
+ }
901
+
902
+ function deleteMetaDataEntry(url) {
903
+ return new Promise(function (resolve, reject) {
904
+ var transaction = self.database.transaction([RequestMetaDataStore.name], "readwrite");
905
+ var target = transaction.objectStore(RequestMetaDataStore.name);
906
+ target.delete(url);
907
+
908
+ transaction.oncomplete = resolve;
909
+ transaction.onerror = reject;
910
+ });
911
+ }
912
+
913
+ function deleteEntries() {
914
+ if (entriesToDelete.length === 0) {
915
+ return Promise.resolve();
916
+ }
917
+
918
+ var entryToDelete = entriesToDelete.pop();
919
+ return self.cache.delete(entryToDelete.url).then(function (deleted) {
920
+ if (deleted) {
921
+ return deleteMetaDataEntry(entryToDelete.url);
922
+ }
923
+ }).then(function () {
924
+ return deleteEntries();
925
+ });
926
+ }
927
+
928
+ return deleteEntries();
929
+ });
930
+ }
931
+
932
+ return UnityCache;
933
+ }();
934
+ Module.cachedFetch = function () {
935
+ var UnityCache = Module.UnityCache;
936
+ var fetchWithProgress = Module.fetchWithProgress;
937
+ var readBodyWithProgress = Module.readBodyWithProgress;
938
+
939
+ function log(message) {
940
+ console.log("[UnityCache] " + message);
941
+ }
942
+
943
+ function resolveURL(url) {
944
+ resolveURL.link = resolveURL.link || document.createElement("a");
945
+ resolveURL.link.href = url;
946
+ return resolveURL.link.href;
947
+ }
948
+
949
+ function isCrossOriginURL(url) {
950
+ var originMatch = window.location.href.match(/^[a-z]+:\/\/[^\/]+/);
951
+ return !originMatch || url.lastIndexOf(originMatch[0], 0);
952
+ }
953
+
954
+ function isCacheEnabled(url, init) {
955
+ if (init && init.method && init.method !== "GET") {
956
+ return false;
957
+ }
958
+
959
+ if (init && ["must-revalidate", "immutable"].indexOf(init.control) == -1) {
960
+ return false;
961
+ }
962
+
963
+ if (!url.match("^https?:\/\/")) {
964
+ return false;
965
+ }
966
+
967
+ return true;
968
+ }
969
+
970
+ function cachedFetch(resource, init) {
971
+ var unityCache = UnityCache.getInstance();
972
+ var url = resolveURL((typeof resource === "string") ? resource : resource.url);
973
+ var cache = { enabled: isCacheEnabled(url, init) };
974
+ if (init) {
975
+ cache.control = init.control;
976
+ cache.companyName = init.companyName;
977
+ cache.productName = init.productName;
978
+ cache.productVersion = init.productVersion;
979
+ }
980
+ cache.revalidated = false;
981
+ cache.metaData = {
982
+ url: url,
983
+ accessedAt: Date.now(),
984
+ version: cache.productVersion
985
+ };
986
+ cache.response = null;
987
+
988
+ function fetchAndStoreInCache(resource, init) {
989
+ return fetch(resource, init).then(function (response) {
990
+ if (!cache.enabled || cache.revalidated) {
991
+ return response;
992
+ }
993
+
994
+ if (response.status === 304) {
995
+ // Cached response is still valid. Set revalidated flag and return cached response
996
+ cache.revalidated = true;
997
+
998
+ unityCache.updateRequestMetaData(cache.metaData).then(function () {
999
+ log("'" + cache.metaData.url + "' successfully revalidated and served from the indexedDB cache");
1000
+ }).catch(function (error) {
1001
+ log("'" + cache.metaData.url + "' successfully revalidated but not stored in the indexedDB cache due to the error: " + error);
1002
+ });
1003
+
1004
+ return readBodyWithProgress(cache.response, init.onProgress);
1005
+ } else if (response.status == 200) {
1006
+ // New response -> Store it and cache and return it
1007
+ cache.response = response;
1008
+ cache.metaData.updatedAt = cache.metaData.accessedAt;
1009
+ cache.revalidated = true;
1010
+ var clonedResponse = response.clone();
1011
+
1012
+ return readBodyWithProgress(response, init.onProgress).then(function (response) {
1013
+ // Update cached request and meta data
1014
+ cache.metaData.size = response.parsedBody.length;
1015
+ Promise.all([
1016
+ unityCache.storeRequest(resource, clonedResponse),
1017
+ unityCache.updateRequestMetaData(cache.metaData)
1018
+ ]).then(function () {
1019
+ log("'" + url + "' successfully downloaded and stored in the indexedDB cache");
1020
+ }).catch(function (error) {
1021
+ log("'" + url + "' successfully downloaded but not stored in the indexedDB cache due to the error: " + error);
1022
+ });
1023
+
1024
+ return response;
1025
+ });
1026
+ } else {
1027
+ // Request failed
1028
+ log("'" + url + "' request failed with status: " + response.status + " " + response.statusText);
1029
+ }
1030
+
1031
+ return readBodyWithProgress(response, init.onProgress);
1032
+ });
1033
+ }
1034
+
1035
+ // Use fetch directly if request can't be cached
1036
+ if (!cache.enabled) {
1037
+ return fetchWithProgress(resource, init);
1038
+ }
1039
+
1040
+ return unityCache.loadRequest(url).then(function (result) {
1041
+ // Fetch resource and store it in cache if not present or outdated version
1042
+ if (!result) {
1043
+ return fetchAndStoreInCache(resource, init);
1044
+ }
1045
+
1046
+ var response = result.response;
1047
+ var metaData = result.metaData;
1048
+ cache.response = response;
1049
+ cache.metaData.size = metaData.size;
1050
+ cache.metaData.updatedAt = metaData.updatedAt;
1051
+
1052
+ if (cache.control == "immutable") {
1053
+ cache.revalidated = true;
1054
+ unityCache.updateRequestMetaData(metaData).then(function () {
1055
+ log("'" + cache.metaData.url + "' served from the indexedDB cache without revalidation");
1056
+ });
1057
+
1058
+ return readBodyWithProgress(response, init.onProgress);
1059
+ } else if (isCrossOriginURL(url) && (response.headers.get("Last-Modified") || response.headers.get("ETag"))) {
1060
+ return fetch(url, { method: "HEAD" }).then(function (headResult) {
1061
+ cache.revalidated = ["Last-Modified", "ETag"].every(function (header) {
1062
+ return !response.headers.get(header) || response.headers.get(header) == headResult.headers.get(header);
1063
+ });
1064
+ if (cache.revalidated) {
1065
+ unityCache.updateRequestMetaData(metaData).then(function () {
1066
+ log("'" + cache.metaData.url + "' successfully revalidated and served from the indexedDB cache");
1067
+ });
1068
+
1069
+ return readBodyWithProgress(cache.response, init.onProgress);
1070
+ } else {
1071
+ return fetchAndStoreInCache(resource, init);
1072
+ }
1073
+ });
1074
+ } else {
1075
+ init = init || {};
1076
+ var requestHeaders = init.headers || {};
1077
+ init.headers = requestHeaders;
1078
+ if (response.headers.get("Last-Modified")) {
1079
+ requestHeaders["If-Modified-Since"] = response.headers.get("Last-Modified");
1080
+ requestHeaders["Cache-Control"] = "no-cache";
1081
+ } else if (response.headers.get("ETag")) {
1082
+ requestHeaders["If-None-Match"] = response.headers.get("ETag");
1083
+ requestHeaders["Cache-Control"] = "no-cache";
1084
+ }
1085
+
1086
+ return fetchAndStoreInCache(resource, init);
1087
+ }
1088
+ }).catch(function (error) {
1089
+ // Fallback to regular fetch if and IndexDB error occurs
1090
+ log("Failed to load '" + cache.metaData.url + "' from indexedDB cache due to the error: " + error);
1091
+ return fetchWithProgress(resource, init);
1092
+ });
1093
+ }
1094
+
1095
+ return cachedFetch;
1096
+ }();
1097
+
1098
+
1099
+ function downloadBinary(urlId) {
1100
+ progressUpdate(urlId);
1101
+ var cacheControl = Module.cacheControl(Module[urlId]);
1102
+ var fetchImpl = Module.companyName && Module.productName ? Module.cachedFetch : Module.fetchWithProgress;
1103
+ var url = Module[urlId];
1104
+ var mode = /file:\/\//.exec(url) ? "same-origin" : undefined;
1105
+
1106
+ var request = fetchImpl(Module[urlId], {
1107
+ method: "GET",
1108
+ companyName: Module.companyName,
1109
+ productName: Module.productName,
1110
+ productVersion: Module.productVersion,
1111
+ control: cacheControl,
1112
+ mode: mode,
1113
+ onProgress: function (event) {
1114
+ progressUpdate(urlId, event);
1115
+ }
1116
+ });
1117
+
1118
+ return request.then(function (response) {
1119
+ return response.parsedBody;
1120
+ }).catch(function (e) {
1121
+ var error = 'Failed to download file ' + Module[urlId];
1122
+ if (location.protocol == 'file:') {
1123
+ showBanner(error + '. Loading web pages via a file:// URL without a web server is not supported by this browser. Please use a local development web server to host Unity content, or use the Unity Build and Run option.', 'error');
1124
+ } else {
1125
+ console.error(error);
1126
+ }
1127
+ });
1128
+ }
1129
+
1130
+ function downloadFramework() {
1131
+ return new Promise(function (resolve, reject) {
1132
+ var script = document.createElement("script");
1133
+ script.src = Module.frameworkUrl;
1134
+ script.onload = function () {
1135
+ // Adding the framework.js script to DOM created a global
1136
+ // 'unityFramework' variable that should be considered internal.
1137
+ // If not, then we have received a malformed file.
1138
+ if (typeof unityFramework === 'undefined' || !unityFramework) {
1139
+ var compressions = [['br', 'br'], ['gz', 'gzip']];
1140
+ for(var i in compressions) {
1141
+ var compression = compressions[i];
1142
+ if (Module.frameworkUrl.endsWith('.' + compression[0])) {
1143
+ var error = 'Unable to parse ' + Module.frameworkUrl + '!';
1144
+ if (location.protocol == 'file:') {
1145
+ showBanner(error + ' Loading pre-compressed (brotli or gzip) content via a file:// URL without a web server is not supported by this browser. Please use a local development web server to host compressed Unity content, or use the Unity Build and Run option.', 'error');
1146
+ return;
1147
+ }
1148
+ error += ' This can happen if build compression was enabled but web server hosting the content was misconfigured to not serve the file with HTTP Response Header "Content-Encoding: ' + compression[1] + '" present. Check browser Console and Devtools Network tab to debug.';
1149
+ if (compression[0] == 'br') {
1150
+ if (location.protocol == 'http:') {
1151
+ var migrationHelp = ['localhost', '127.0.0.1'].indexOf(location.hostname) != -1 ? '' : 'Migrate your server to use HTTPS.'
1152
+ if (/Firefox/.test(navigator.userAgent)) error = 'Unable to parse ' + Module.frameworkUrl + '!<br>If using custom web server, verify that web server is sending .br files with HTTP Response Header "Content-Encoding: br". Brotli compression may not be supported in Firefox over HTTP connections. ' + migrationHelp + ' See <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1670675">https://bugzilla.mozilla.org/show_bug.cgi?id=1670675</a> for more information.';
1153
+ else error = 'Unable to parse ' + Module.frameworkUrl + '!<br>If using custom web server, verify that web server is sending .br files with HTTP Response Header "Content-Encoding: br". Brotli compression may not be supported over HTTP connections. Migrate your server to use HTTPS.';
1154
+ }
1155
+ }
1156
+ showBanner(error, 'error');
1157
+ return;
1158
+ }
1159
+ };
1160
+ showBanner('Unable to parse ' + Module.frameworkUrl + '! The file is corrupt, or compression was misconfigured? (check Content-Encoding HTTP Response Header on web server)', 'error');
1161
+ }
1162
+
1163
+ // Capture the variable to local scope and clear it from global
1164
+ // scope so that JS garbage collection can take place on
1165
+ // application quit.
1166
+ var fw = unityFramework;
1167
+ unityFramework = null;
1168
+ // Also ensure this function will not hold any JS scope
1169
+ // references to prevent JS garbage collection.
1170
+ script.onload = null;
1171
+ resolve(fw);
1172
+ }
1173
+ script.onerror = function(e) {
1174
+ showBanner('Unable to load file ' + Module.frameworkUrl + '! Check that the file exists on the remote server. (also check browser Console and Devtools Network tab to debug)', 'error');
1175
+ }
1176
+ document.body.appendChild(script);
1177
+ Module.deinitializers.push(function() {
1178
+ document.body.removeChild(script);
1179
+ });
1180
+ });
1181
+ }
1182
+
1183
+ function loadBuild() {
1184
+ downloadFramework().then(function (unityFramework) {
1185
+ unityFramework(Module);
1186
+ });
1187
+
1188
+ var dataPromise = downloadBinary("dataUrl");
1189
+ Module.preRun.push(function () {
1190
+ Module.addRunDependency("dataUrl");
1191
+ dataPromise.then(function (data) {
1192
+ var view = new DataView(data.buffer, data.byteOffset, data.byteLength);
1193
+ var pos = 0;
1194
+ var prefix = "UnityWebData1.0\0";
1195
+ if (!String.fromCharCode.apply(null, data.subarray(pos, pos + prefix.length)) == prefix)
1196
+ throw "unknown data format";
1197
+ pos += prefix.length;
1198
+ var headerSize = view.getUint32(pos, true); pos += 4;
1199
+ while (pos < headerSize) {
1200
+ var offset = view.getUint32(pos, true); pos += 4;
1201
+ var size = view.getUint32(pos, true); pos += 4;
1202
+ var pathLength = view.getUint32(pos, true); pos += 4;
1203
+ var path = String.fromCharCode.apply(null, data.subarray(pos, pos + pathLength)); pos += pathLength;
1204
+ for (var folder = 0, folderNext = path.indexOf("/", folder) + 1 ; folderNext > 0; folder = folderNext, folderNext = path.indexOf("/", folder) + 1)
1205
+ Module.FS_createPath(path.substring(0, folder), path.substring(folder, folderNext - 1), true, true);
1206
+ Module.FS_createDataFile(path, null, data.subarray(offset, offset + size), true, true, true);
1207
+ }
1208
+ Module.removeRunDependency("dataUrl");
1209
+ });
1210
+ });
1211
+ }
1212
+
1213
+ return new Promise(function (resolve, reject) {
1214
+ if (!Module.SystemInfo.hasWebGL) {
1215
+ reject("Your browser does not support WebGL.");
1216
+ } else if (Module.SystemInfo.hasWebGL == 1) {
1217
+ var msg = "Your browser does not support graphics API \"WebGL 2\" which is required for this content.";
1218
+ if (Module.SystemInfo.browser == 'Safari' && parseInt(Module.SystemInfo.browserVersion) < 15) {
1219
+ if (Module.SystemInfo.mobile || navigator.maxTouchPoints > 1)
1220
+ msg += "\nUpgrade to iOS 15 or later.";
1221
+ else
1222
+ msg += "\nUpgrade to Safari 15 or later.";
1223
+ }
1224
+ reject(msg);
1225
+ } else if (!Module.SystemInfo.hasWasm) {
1226
+ reject("Your browser does not support WebAssembly.");
1227
+ } else {
1228
+ Module.startupErrorHandler = reject;
1229
+ onProgress(0);
1230
+ Module.postRun.push(function () {
1231
+ onProgress(1);
1232
+ delete Module.startupErrorHandler;
1233
+ resolve(unityInstance);
1234
+ });
1235
+ loadBuild();
1236
+ }
1237
+ });
1238
+ }
Build/SimplifiedTerrain-simpleMovement-light-demo-webgl-dev.wasm ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1e26bc6578336a90e35cd57ac23b13f751231b909ef6b106ef9ada1619ddd45a
3
+ size 47060545
StreamingAssets/UnityServicesProjectConfiguration.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"Keys":["com.unity.services.core.cloud-environment","com.unity.services.core.version"],"Values":[{"m_Value":"production","m_IsReadOnly":true},{"m_Value":"1.4.2","m_IsReadOnly":true}]}
TemplateData/favicon.ico ADDED
TemplateData/fullscreen-button.png ADDED
TemplateData/style.css ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ html {
2
+ box-sizing: border-box;
3
+ }
4
+ *, *:before, *:after {
5
+ box-sizing: inherit;
6
+ }
7
+ html, body {
8
+ height: 100%;
9
+ }
10
+ canvas {
11
+ display: block;
12
+ }
13
+ body {
14
+ margin: 0;
15
+ }
16
+ #unity-container {
17
+ width: 100%;
18
+ height: 100%;
19
+ }
20
+ #unity-canvas {
21
+ width: 100%;
22
+ height: 100%;
23
+ background: #231F20;
24
+ }
25
+ #loading-cover {
26
+ position: absolute;
27
+ top: 0;
28
+ left: 0;
29
+ width: 100%;
30
+ height: 100%;
31
+ display: flex;
32
+ justify-content: center;
33
+ align-items: center;
34
+ }
35
+ #unity-loading-bar {
36
+ flex: 1 1 auto;
37
+ display: flex;
38
+ flex-direction: column;
39
+ justify-content: center;
40
+ align-items: center;
41
+ }
42
+ #unity-logo {
43
+ text-align: center;
44
+ }
45
+ #unity-logo img {
46
+ max-width: 80%;
47
+ }
48
+ #unity-progress-bar-empty {
49
+ width: 80%;
50
+ height: 24px;
51
+ margin: 10px 20px 20px 10px;
52
+ text-align: left;
53
+ border: 1px solid white;
54
+ padding: 2px;
55
+ }
56
+ #unity-progress-bar-full {
57
+ width: 0%;
58
+ height: 100%;
59
+ background: #ffd21e;
60
+ }
61
+ .light #unity-progress-bar-empty {
62
+ border-color: black;
63
+ }
64
+ .light #unity-progress-bar-full {
65
+ background: black;
66
+ }
67
+
68
+ #unity-fullscreen-button {
69
+ position: absolute;
70
+ right: 10px;
71
+ bottom: 10px;
72
+ width: 38px;
73
+ height: 38px;
74
+ background: url('fullscreen-button.png') no-repeat center;
75
+ background-size: contain;
76
+ }
77
+
78
+ .spinner,
79
+ .spinner:after {
80
+ border-radius: 50%;
81
+ width: 5em;
82
+ height: 5em;
83
+ }
84
+ .spinner {
85
+ margin: 10px;
86
+ font-size: 10px;
87
+ position: relative;
88
+ text-indent: -9999em;
89
+ border-top: 1.1em solid rgba(255, 255, 255, 0.2);
90
+ border-right: 1.1em solid rgba(255, 255, 255, 0.2);
91
+ border-bottom: 1.1em solid rgba(255, 255, 255, 0.2);
92
+ border-left: 1.1em solid #ffffff;
93
+ transform: translateZ(0);
94
+ animation: spinner-spin 1.1s infinite linear;
95
+ }
96
+ @keyframes spinner-spin {
97
+ 0% {
98
+ transform: rotate(0deg);
99
+ }
100
+ 100% {
101
+ transform: rotate(360deg);
102
+ }
103
+ }
104
+
105
+
index.html CHANGED
@@ -1,24 +1,216 @@
1
- <!DOCTYPE html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width" />
6
- <title>My static Space</title>
7
- <link rel="stylesheet" href="style.css" />
8
- </head>
9
- <body>
10
- <div class="card">
11
- <h1>Welcome to your static Space!</h1>
12
- <p>
13
- You can modify this app directly by editing <i>index.html</i> in the
14
- Files and versions tab.
15
- </p>
16
- <p>
17
- Also don't forget to check the
18
- <a href="https://huggingface.co/docs/hub/spaces" target="_blank"
19
- >Spaces documentation</a
20
- >.
21
- </p>
22
- </div>
23
- </body>
24
- </html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en-us">
3
+
4
+ <head>
5
+ <meta charset="utf-8">
6
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
7
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
8
+ <title>excav_simul_3d</title>
9
+ <link rel="shortcut icon" href="TemplateData/favicon.ico">
10
+ <link rel="stylesheet" href="TemplateData/style.css">
11
+ <link rel="stylesheet" href="main.css">
12
+ </head>
13
+
14
+ <body class="dark">
15
+ <div id="unity-container" class="unity-desktop">
16
+ <canvas id="unity-canvas"></canvas>
17
+ </div>
18
+ <div id="loading-cover" style="display:none;">
19
+ <div id="unity-loading-bar">
20
+ <div id="unity-logo"><img src="logo.png"></div>
21
+ <div id="unity-progress-bar-empty" style="display: none;">
22
+ <div id="unity-progress-bar-full"></div>
23
+ </div>
24
+ <div class="spinner"></div>
25
+ </div>
26
+ </div>
27
+ <div id="unity-fullscreen-button" style="display: none;"></div>
28
+ <script>
29
+ const hideFullScreenButton = "";
30
+ const buildUrl = "Build";
31
+ const loaderUrl = buildUrl + "/SimplifiedTerrain-simpleMovement-light-demo-webgl-dev.loader.js";
32
+ const config = {
33
+ dataUrl: buildUrl + "/SimplifiedTerrain-simpleMovement-light-demo-webgl-dev.data",
34
+ frameworkUrl: buildUrl + "/SimplifiedTerrain-simpleMovement-light-demo-webgl-dev.framework.js",
35
+ codeUrl: buildUrl + "/SimplifiedTerrain-simpleMovement-light-demo-webgl-dev.wasm",
36
+ streamingAssetsUrl: "StreamingAssets",
37
+ companyName: "DefaultCompany",
38
+ productName: "excav_simul_3d",
39
+ productVersion: "0.1",
40
+ };
41
+
42
+ const container = document.querySelector("#unity-container");
43
+ const canvas = document.querySelector("#unity-canvas");
44
+ const loadingCover = document.querySelector("#loading-cover");
45
+ const progressBarEmpty = document.querySelector("#unity-progress-bar-empty");
46
+ const progressBarFull = document.querySelector("#unity-progress-bar-full");
47
+ const fullscreenButton = document.querySelector("#unity-fullscreen-button");
48
+ const spinner = document.querySelector('.spinner');
49
+
50
+ const canFullscreen = (function () {
51
+ for (const key of [
52
+ 'exitFullscreen',
53
+ 'webkitExitFullscreen',
54
+ 'webkitCancelFullScreen',
55
+ 'mozCancelFullScreen',
56
+ 'msExitFullscreen',
57
+ ]) {
58
+ if (key in document) {
59
+ return true;
60
+ }
61
+ }
62
+ return false;
63
+ }());
64
+
65
+ if (/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)) {
66
+ container.className = "unity-mobile";
67
+ config.devicePixelRatio = 1;
68
+ }
69
+ loadingCover.style.display = "";
70
+
71
+ const script = document.createElement("script");
72
+ script.src = loaderUrl;
73
+ script.onload = () => {
74
+ createUnityInstance(canvas, config, (progress) => {
75
+ spinner.style.display = "none";
76
+ progressBarEmpty.style.display = "";
77
+ progressBarFull.style.width = `${100 * progress}%`;
78
+ }).then((unityInstance) => {
79
+ loadingCover.style.display = "none";
80
+ if (canFullscreen) {
81
+ if (!hideFullScreenButton) {
82
+ fullscreenButton.style.display = "";
83
+ }
84
+ fullscreenButton.onclick = () => {
85
+ unityInstance.SetFullscreen(1);
86
+ };
87
+ }
88
+ }).catch((message) => {
89
+ alert(message);
90
+ });
91
+ };
92
+ document.body.appendChild(script);
93
+ </script>
94
+ <div id="infoBox">
95
+ <h1>Controls</h1>
96
+ <div id="controls">
97
+ <table>
98
+ <th>Binding</th>
99
+ <th>Description</th>
100
+ <tr>
101
+ <td>Right Mouse Click (Drag)</td>
102
+ <td>
103
+ Rotates the camera in the direction of the mouse drag.
104
+ </td>
105
+ </tr>
106
+ <tr>
107
+ <td>Left Mouse Click</td>
108
+ <td>
109
+ Sets the goal point to the location on the terrain where you clicked.
110
+ </td>
111
+ </tr>
112
+ <tr>
113
+ <td>W</td>
114
+ <td>
115
+ Move forward.
116
+ </td>
117
+ </tr>
118
+ <tr>
119
+ <td>S</td>
120
+ <td>
121
+ Move backward.
122
+ </td>
123
+ </tr>
124
+ <tr>
125
+ <td>A</td>
126
+ <td>
127
+ Move left.
128
+ </td>
129
+ </tr>
130
+ <tr>
131
+ <td>D</td>
132
+ <td>
133
+ Move right.
134
+ </td>
135
+ </tr>
136
+ <tr>
137
+ <td>E</td>
138
+ <td>Move up.</td>
139
+ </tr>
140
+ <tr>
141
+ <td>Q</td>
142
+ <td>Move down.</td>
143
+ </tr>
144
+ <tr>
145
+ <td>R</td>
146
+ <td>
147
+ Restart the episode.
148
+ Note that the terrain does not change even if you are in random mode.
149
+ Deformations to the terrain are preserved as well.
150
+ </td>
151
+ </tr>
152
+ <tr>
153
+ <td>1</td>
154
+ <td>
155
+ <div class="cellHeader">Terrain Mode: RANDOM</div>
156
+ Restart with a random terrain shape (no perlin noise).
157
+ </td>
158
+ </tr>
159
+ <tr>
160
+ <td>2</td>
161
+ <td>
162
+ <div class="cellHeader">Terrain Mode: RANDOM_NOISE</div>
163
+ Restart with a random terrain shape (with perlin noise).
164
+ </td>
165
+ </tr>
166
+ <tr>
167
+ <td>3</td>
168
+ <td>
169
+ <div class="cellHeader">Terrain Mode: GAUSSIAN_SLOPE</div>
170
+ Restart with a gaussian slope shaped terrain.
171
+ </td>
172
+ </tr>
173
+ <tr>
174
+ <td>4</td>
175
+ <td>
176
+ <div class="cellHeader">Terrain Mode: POINTY_GAUSSIAN_SLOPE</div>
177
+ Restart with a <i>pointy</i> gaussian slope shaped terrain.
178
+ </td>
179
+ </tr>
180
+ <tr>
181
+ <td>5</td>
182
+ <td>
183
+ <div class="cellHeader">Terrain Mode: TRAPEZOIDAL_HILL</div>
184
+ Restart with a trapezoidal hill shaped terrain.
185
+ </td>
186
+ </tr>
187
+ </table>
188
+ </div>
189
+ <h1>Disclaimer</h1>
190
+ <div id="disclaimerBody">
191
+ <p>
192
+ <a target=”_blank” href="https://docs.unity3d.com/Packages/com.unity.ml-agents@2.2/manual/index.html#inference">
193
+ Unfortunately, MLAgents doesn't support GPU inference for WebGL builds.
194
+ </a><br>
195
+ The excavator model was originally trained with a larger neural network and yielded good results, but the model
196
+ was too large to run smoothly on the CPU.
197
+ The current model was trained with a smaller model. Although it can run more smoothly on the CPU, the
198
+ performance isn't as good as that of the larger model.
199
+ </p>
200
+ <p>
201
+ If you would like to try out the larger model as well, refer to <a
202
+ href="https://huggingface.co/spaces/cm107/excav_demo">excav_demo</a>.
203
+ When using the larger model, it is recommended that you download the build corresponding to your specific target
204
+ platform.
205
+ </p>
206
+ <p>
207
+ For more information about WebGL performance considerations, refer to
208
+ <a target=”_blank” href="https://docs.unity3d.com/Manual/webgl-performance.html">
209
+ the unity documentation
210
+ </a>.
211
+ </p>
212
+ </div>
213
+ </div>
214
+ </body>
215
+
216
+ </html>
logo.png ADDED
main.css ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #infoBox {
2
+ /* border: 5px solid red; */
3
+ width: 75%;
4
+ margin-left: auto;
5
+ margin-right: auto;
6
+ }
7
+
8
+ #controls {
9
+ margin-left: auto;
10
+ margin-right: auto;
11
+ margin-top: auto;
12
+ margin-bottom: auto;
13
+ justify-content: center;
14
+ justify-items: center;
15
+ }
16
+
17
+ table {
18
+ display: table;
19
+ justify-content: center;
20
+ margin-left: auto;
21
+ margin-right: auto;
22
+ }
23
+
24
+ table,
25
+ th,
26
+ td {
27
+ border: 1px solid;
28
+ border-collapse: collapse;
29
+ }
30
+
31
+ td {
32
+ justify-content: right;
33
+ }
34
+
35
+ .cellHeader {
36
+ display: flex;
37
+ color: purple;
38
+ justify-content: center;
39
+
40
+ }
41
+
42
+ #disclaimerBody {
43
+ color: red;
44
+ margin-left: 30px;
45
+ }