File: app.html

package info (click to toggle)
f3d 3.2.0%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 27,668 kB
  • sloc: cpp: 99,109; python: 811; sh: 342; xml: 238; java: 101; javascript: 95; makefile: 25
file content (489 lines) | stat: -rw-r--r-- 18,956 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
<!doctype html>
<html class="theme-dark">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>F3D Web</title>
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/bulma@1.0.0/css/bulma.min.css"
    />
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/bulma-switch@2.0.4/dist/css/bulma-switch.min.css"
    />
    <link rel="manifest" href="manifest.json" />
    <style>
      #main {
        min-height: 70vh;
      }
    </style>
  </head>

  <body>
    <section class="section">
      <div class="notification is-warning">
        <button class="delete"></button>
        This web application is experimental and currently not well tested. It's
        deployed continuously and can break at anytime. Don't hesitate to reach
        out on <a href="https://discord.f3d.app">Discord</a>
        if it's currently not working or if you want to contribute.
      </div>
      <div class="columns">
        <div class="column">
          <h1 class="title">F3D Web</h1>
          <p class="subtitle">A WebAssembly application using libf3d</p>
        </div>
        <div class="column">
          <div class="field is-pulled-right">
            <input
              id="dark"
              type="checkbox"
              name="dark"
              class="switch is-rounded"
              checked
            />
            <label for="dark">Dark theme</label>
          </div>
        </div>
      </div>
    </section>
    <section class="section">
      <div class="columns">
        <aside class="menu">
          <div class="file has-name">
            <label class="file-label">
              <input
                class="file-input"
                type="file"
                id="file-selector"
                accept=".gml,.gltf,.glb,.obj,.ply,.pts,.stl,.vtk,.vtp,.vtu,.vtkhdf,.3ds,.wrl,.vrml,.fbx,.off,.x,.dae,.ex2,.exo,.e,.stp,.step,.igs,.iges,.brep,.xbf,.drc,.mdl"
              />
              <span class="file-cta">
                <span class="file-label">Open a file...</span>
              </span>
              <span class="file-name" id="file-name"></span>
            </label>
          </div>
          <div class="is-flex is-flex-direction-row is-align-items-center">
            <button id="y-up" class="button mx-1 is-small">+Y</button>
            <button id="z-up" class="button mx-1 is-small is-active">+Z</button>
            <label class="mx-1">Up</label>
          </div>
          <p class="menu-label">Widgets</p>
          <div class="field">
            <input
              id="grid"
              type="checkbox"
              name="grid"
              class="switch is-rounded"
              checked
            />
            <label for="grid">Grid</label>
          </div>
          <div class="field">
            <input
              id="axis"
              type="checkbox"
              name="axis"
              class="switch is-rounded"
              checked
            />
            <label for="axis">Axis</label>
          </div>
          <p class="menu-label">Rendering</p>
          <div class="field">
            <input
              id="fxaa"
              type="checkbox"
              name="fxaa"
              class="switch is-rounded"
              checked
            />
            <label for="fxaa">Anti-aliasing</label>
          </div>
          <div class="field">
            <input
              id="tone"
              type="checkbox"
              name="tone"
              class="switch is-rounded"
              checked
            />
            <label for="tone">Tone mapping</label>
          </div>
          <div class="field">
            <input
              id="ssao"
              type="checkbox"
              name="ssao"
              class="switch is-rounded"
              checked
            />
            <label for="ssao">Ambient occlusion</label>
          </div>
          <p class="menu-label">Lighting</p>
          <div class="field">
            <input
              id="ambient"
              type="checkbox"
              name="ambient"
              class="switch is-rounded"
              checked
            />
            <label for="ambient">Ambient light</label>
          </div>
        </aside>
        <div class="column">
          <div class="container" id="main">
            <canvas id="canvas"></canvas>
          </div>
        </div>
      </div>
      <div
        class="event-log"
        style="
          position: absolute;
          z-index: 10;
          bottom: 50px;
          width: 100%;
          display: none;
        "
      >
        <p style="text-align: center">Loading 3D object...</p>
        <progress
          class="progress is-primary"
          id="progressEl"
          value="0"
          max="100"
          style="transition: all 2s; width: 500px; margin: auto"
        >
          30%
        </progress>
      </div>
    </section>
    <script type="text/javascript" src="f3d.js"></script>
    <script type="text/javascript">
      // remove warning when delete button is clicked
      (document.querySelectorAll(".notification .delete") || []).forEach(
        ($delete) => {
          const $notification = $delete.parentNode;

          $delete.addEventListener("click", () => {
            $notification.parentNode.removeChild($notification);
          });
        },
      );

      const settings = {
        canvas: document.getElementById("canvas"),
        setupOptions: (options) => {
          // background must be set to black for proper blending with transparent canvas
          options.set_color("render.background.color", 0, 0, 0);

          // setup coloring
          options.toggle("model.scivis.enable");
          options.set_string("model.scivis.array_name", "Colors");
          options.set_integer("model.scivis.component", -2);
          options.toggle("model.scivis.cells");

          // make it look nice
          options.toggle("render.effect.antialiasing.enable");
          options.toggle("render.effect.tone_mapping");
          options.toggle("render.effect.ambient_occlusion");
          options.toggle("render.hdri.ambient");

          // display widgets
          options.toggle("ui.axis");
          options.toggle("render.grid.enable");

          // default to +Z
          options.set_as_string("scene.up_direction", "+Z");
        },
      };

      f3d(settings)
        .then((Module) => {
          // automatically load all supported file format readers
          Module.Engine.autoloadPlugins();

          Module.engineInstance = Module.Engine.create();

          const openFile = (name) => {
            document.getElementById("file-name").innerHTML = name;
            const filePath = "/" + name;
            const scene = Module.engineInstance.getScene();
            if (scene.supports(filePath)) {
              scene.clear();
              scene.add(filePath);
            } else {
              console.error("File " + filePath + " cannot be opened");
            }
            Module.engineInstance.getWindow().resetCamera();
            Module.engineInstance.getWindow().render();
          };

          // setup file open event
          const progressEl = document.querySelector("#progressEl");
          const fileSelector = document.querySelector("#file-selector");
          fileSelector.addEventListener("change", (evt) => {
            for (const file of evt.target.files) {
              const reader = new FileReader();
              reader.addEventListener("loadend", (e) => {
                progressEl.textContent = "100%";
                progressEl.value = 100;
                Module.FS.writeFile(file.name, new Uint8Array(reader.result));
                openFile(file.name);
                progressEl.parentElement.style.display = "none";
              });
              reader.addEventListener("progress", (evt) => {
                console.log(evt);
                const progress = Math.floor((100 * evt.loaded) / evt.total);
                progressEl.parentElement.style.display = "block";
                progressEl.value = progress;
                progressEl.textContent = `${progress}%`;
              });
              reader.readAsArrayBuffer(file);
            }
          });

          Module.setupOptions(Module.engineInstance.getOptions());

          // Storing dom el ids to f3d option mappings since also useful for url-param parsing
          const idOptionMappings = [
            ["grid", "render.grid.enable"],
            ["axis", "ui.axis"],
            ["fxaa", "render.effect.antialiasing.enable"],
            ["tone", "render.effect.tone_mapping"],
            ["ssao", "render.effect.ambient_occlusion"],
            ["ambient", "render.hdri.ambient"],
          ];

          // toggle callback
          const mapToggleIdToOption = (id, option) => {
            document
              .querySelector("#" + id)
              .addEventListener("change", (evt) => {
                Module.engineInstance.getOptions().toggle(option);
                Module.engineInstance.getWindow().render();
              });
          };

          // This assumes all toggles are 'on' before mapping their state to options
          // Ok after f3d(settings) where settings = {..., setupOptions} which toggles some options
          for (let [id, option] of idOptionMappings) {
            mapToggleIdToOption(id, option);
          }

          switchDark = () => {
            document.documentElement.classList.add("theme-dark");
            document.documentElement.classList.remove("theme-light");
            Module.engineInstance
              .getOptions()
              .set_color("render.grid.color", 0.25, 0.27, 0.33);
            Module.engineInstance.getWindow().render();
          };

          switchLight = () => {
            document.documentElement.classList.add("theme-light");
            document.documentElement.classList.remove("theme-dark");
            Module.engineInstance
              .getOptions()
              .set_color("render.grid.color", 0.67, 0.69, 0.75);
            Module.engineInstance.getWindow().render();
          };

          // theme switch
          document.querySelector("#dark").addEventListener("change", (evt) => {
            if (evt.target.checked) switchDark();
            else switchLight();
          });

          switchDark();

          // up callback
          document.querySelector("#z-up").addEventListener("click", (evt) => {
            Module.engineInstance
              .getOptions()
              .set_as_string("scene.up_direction", "+Z");
            document.getElementById("z-up").classList.add("is-active");
            document.getElementById("y-up").classList.remove("is-active");
            openFile(document.getElementById("file-name").innerHTML);
          });

          document.querySelector("#y-up").addEventListener("click", (evt) => {
            Module.engineInstance
              .getOptions()
              .set_as_string("scene.up_direction", "+Y");
            document.getElementById("y-up").classList.add("is-active");
            document.getElementById("z-up").classList.remove("is-active");
            openFile(document.getElementById("file-name").innerHTML);
          });

          // setup the window size based on the canvas size
          const main = document.getElementById("main");
          const scale = window.devicePixelRatio;
          Module.engineInstance
            .getWindow()
            .setSize(scale * main.clientWidth, scale * main.clientHeight);

          // do a first render and start the interactor
          Module.engineInstance.getWindow().render();
          Module.engineInstance.getInteractor().start();

          // Parse model from url-param search query hash via model url and extension
          function filename_for_model_url(
            model_url,
            extension_parsed,
            contentDisposition,
          ) {
            // Build filename given extension urlparam or response header content-disposition
            if (extension_parsed) {
              return `model_urlparam.${extension_parsed}`;
            } else if (contentDisposition) {
              // If extension is not provided by user, try to get it auto from content-disposition header of url extension
              return contentDisposition.split("filename=")[1].split(";")[0];
            } else {
              return model_url.split("/").pop();
            }
            throw new Error(
              `Could not parse filename/extension from either urlparam extension, response header content-disposition, nor filename present in url`,
            );
          }

          // Have fetch support onProgress event
          async function fetchWithProgress(url, onProgress) {
            const response = await fetch(url);
            if (!response.ok) {
              throw new Error(`HTTP error! status: ${response.status}`);
            }
            const contentLength = response.headers.get("Content-Length");
            if (!contentLength) {
              console.warn("Content-Length header is missing");
            }
            const total = contentLength ? parseInt(contentLength, 10) : 0;
            let loaded = 0;
            const reader = response.body.getReader();
            const stream = new ReadableStream({
              start(controller) {
                function push() {
                  reader
                    .read()
                    .then(({ done, value }) => {
                      if (done) {
                        controller.close();
                        return;
                      }
                      loaded += value.length;
                      if (onProgress) {
                        onProgress(loaded, total);
                      }
                      controller.enqueue(value);
                      push();
                    })
                    .catch((err) => {
                      console.error("Stream reading error:", err);
                      controller.error(err);
                    });
                }
                push();
              },
            });
            return new Response(stream);
          }
          function onFetchProgress(loaded, total) {
            const progress = Math.floor((100 * loaded) / total);
            progressEl.parentElement.style.display = "block";
            progressEl.value = progress;
            progressEl.textContent = `${progress}%`;
            console.log(`${progress}%`, loaded, total);
          }

          // Parse search-query model url-param or load default model file
          function load_from_url() {
            // const params = new URLSearchParams(window.location.search);
            // Replace first hash with question mark to have real search query parsing and avoid leading # in first parsed urlparam
            const params = new URLSearchParams(
              window.location.hash.replace(/^#/, "?"),
            );
            const model_url_passed = params.get("model");
            const extension_parsed = params.get("extension");
            if (model_url_passed) {
              const model_url = decodeURI(model_url_passed);
              fetchWithProgress(model_url, onFetchProgress)
                // fetch(model_url)
                .then((response) => {
                  if (!response.ok) {
                    throw new Error(`HTTP error, status = ${response.status}`);
                  }
                  const contentDisposition = response.headers.get(
                    "content-disposition",
                  );
                  const filename = filename_for_model_url(
                    model_url,
                    extension_parsed,
                    contentDisposition,
                  );
                  // Convert buffer to Uint8Array and openFile
                  response.arrayBuffer().then((buffer) => {
                    Module.FS.writeFile(filename, new Uint8Array(buffer));
                    openFile(filename);
                    progressEl.parentElement.style.display = "none";
                  });
                })
                .catch(function (error) {
                  console.log("error caught during fetch", error);
                  alert(
                    "Error occurred while fetching the model at provided url (passed as url-param). \n\nThis might be a CORS issue (you can avoid it by using a Allow-CORS plugin) because server does not allow cross-origin requests, or the url to the file is wrong. \n\nComplete error message: " +
                      error.message,
                  );
                });
            } else {
              // load the file located in the virtual filesystem
              openFile("f3d.vtp");
            }

            // Parse other options like #axis=false&grid=false&fxaa=false&tone=false&ssao=false&ambient=false
            const options = Module.engineInstance.getOptions();
            for (let [id, option] of idOptionMappings) {
              // Set f3d option parameter values
              const parsed_param_value = params.get(id);
              if (parsed_param_value) {
                // Let set_as_string handle value conversion and validation.
                options.set_as_string(option, parsed_param_value.toLowerCase());
                // However, get_as_string returns string rather than typed value
                const new_val = options.get_as_string(option) == "true";
                ui_switch = document.querySelector("#" + id);
                if (ui_switch) ui_switch.checked = new_val;
              }
            }

            // Parse up vector and update UI, up is either +Z or +Y
            // + Plus sign means spaces in urls, so +Z has to be replaced by %2BZ
            const parsed_up_value = params.get("up");
            if (parsed_up_value) {
              console.log("up", parsed_up_value);
              options.set_string("scene.up_direction", parsed_up_value);
              for (const el of ["z-up", "y-up"])
                document.getElementById(el).classList.remove("is-active");
              if (parsed_up_value == "+Y") {
                document.getElementById("y-up").classList.add("is-active");
              } else {
                document.getElementById("z-up").classList.add("is-active");
              }
              openFile(document.getElementById("file-name").innerHTML);
            }

            // Needs re-render to update F3D options
            Module.engineInstance.getWindow().render();
          }
          addEventListener("hashchange", (event) => {
            load_from_url();
          });
          load_from_url();
        })
        .catch((error) => console.error("Internal exception: " + error));
    </script>
  </body>
</html>