/ challenges-old / plate-solutions
Sign in
challenges-old / plate-solutions
plate-solutions / web / viewer.js
248 lines · 11.0 KBCodeBlameHistory
c689df2Add kirchhoff-bfs submission for plate-strike-v1 (meshes 4 to 48), field export via LFS, and this repository's site with a 3D field viewerJeremy Magland 1// Lists this repository's submissions and animates the exported HDF5 displacement fields as a 3D surface.
2import * as THREE from "three";
3import { OrbitControls } from "three/addons/controls/OrbitControls.js";
4import h5wasm from "https://cdn.jsdelivr.net/npm/h5wasm@0.7/dist/esm/hdf5_hl.js";
6const manifest = await (await fetch("manifest.json")).json();
7const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
9// ---------------------------------------------------------------- submissions table
10const subsDiv = document.getElementById("submissions");
11const fieldSolutions = [];
12for (const [cid, ch] of Object.entries(manifest.challenges)) {
13 const h3 = document.createElement("h3");
14 h3.textContent = cid;
15 subsDiv.appendChild(h3);
16 for (const sub of ch.submissions) {
17 const p = document.createElement("p");
18 p.innerHTML = `<b>${esc(sub.submission_id)}</b> by ${esc(sub.submitter.name)}${sub.date ? " (" + esc(sub.date) + ")" : ""}. ${esc(sub.description || "")}` +
19 (sub.code_url ? ` <a href="${esc(sub.code_url)}">code</a>` : "");
20 subsDiv.appendChild(p);
21 const rows = sub.solutions.map((s) => {
22 if (s.fields && s.fields.available !== false) fieldSolutions.push({ label: `${sub.submission_id}/${s.solution_id}`, path: s.fields.path });
23 const fieldsLink = s.fields ? (s.fields.available === false ? ' <span class="muted">(fields stored in LFS, not published here)</span>' : ` <a href="${esc(s.fields.path)}">fields</a>`) : "";
24 return `<tr><td>${esc(s.solution_id)}</td><td>${esc(s.method || "")}<br><span class="muted"><code>${esc(JSON.stringify(s.parameters || {}))}</code></span></td>` +
25 `<td class="num">${s.timing_seconds ?? ""}</td><td class="muted">${esc((s.more_accurate_than || []).join(", "))}</td>` +
26 `<td><div class="cplayer" data-src="${esc(s.output)}"></div><br><a href="${esc(s.output)}">wav</a>${fieldsLink}</td></tr>`;
27 }).join("");
28 const wrap = document.createElement("div");
29 wrap.className = "wrap";
30 wrap.innerHTML = `<table><tr><th>Solution</th><th>Method</th><th>Time (s)</th><th>Claimed more accurate than</th><th>Output</th></tr>${rows}</table>`;
31 subsDiv.appendChild(wrap);
32 }
35const gains = manifest.playback_gain_db || {};
36const firstGain = Object.values(gains).find((g) => typeof g === "number");
37ChallengePlayer.controls(document.getElementById("playback"), { gainDb: typeof firstGain === "number" ? firstGain : 20, limiter: true });
38ChallengePlayer.mount();
40// ---------------------------------------------------------------- 3D viewer
41const view = document.getElementById("view");
42const status = document.getElementById("fieldStatus");
43const select = document.getElementById("fieldSelect");
44const playBtn = document.getElementById("playBtn");
45const speed = document.getElementById("speed");
46const speedLabel = document.getElementById("speedLabel");
47const exag = document.getElementById("exag");
48const exagLabel = document.getElementById("exagLabel");
49const timeSlider = document.getElementById("timeSlider");
7141e28Add vonkarman-modal submission for plate-strike-nl-v1; viewer removes rigid motionJeremy Magland 50const derigid = document.getElementById("derigid");
53const renderer = new THREE.WebGLRenderer({ antialias: true });
54renderer.setPixelRatio(window.devicePixelRatio || 1);
55view.appendChild(renderer.domElement);
56const scene = new THREE.Scene();
57const dark = matchMedia("(prefers-color-scheme: dark)").matches;
58scene.background = new THREE.Color(dark ? 0x151515 : 0xffffff);
59const camera = new THREE.PerspectiveCamera(40, 2, 0.01, 100);
60camera.position.set(0.35, -0.5, 0.35);
61camera.up.set(0, 0, 1);
62const controls = new OrbitControls(camera, renderer.domElement);
63controls.target.set(0, 0, 0);
64scene.add(new THREE.AmbientLight(0xffffff, 0.6));
65const dl = new THREE.DirectionalLight(0xffffff, 0.9);
66dl.position.set(0.5, -0.8, 1.0);
67scene.add(dl);
69let field = null; // {x, y, t, u, nx, ny, nt, umax}
70let mesh = null;
71let frame = 0;
72let playing = false;
73let lastTs = null;
74let simTime = 0;
76function resize() {
77 const w = view.clientWidth, h = view.clientHeight;
78 renderer.setSize(w, h, false);
79 camera.aspect = w / h;
80 camera.updateProjectionMatrix();
82window.addEventListener("resize", () => { resize(); render(); });
83resize();
85function buildMesh() {
86 if (mesh) { scene.remove(mesh); mesh.geometry.dispose(); mesh.material.dispose(); }
87 const { x, y, nx, ny } = field;
88 const Lx = x[nx - 1], Ly = y[ny - 1];
89 const geo = new THREE.PlaneGeometry(Lx, Ly, nx - 1, ny - 1);
90 geo.translate(0, 0, 0);
91 const colors = new Float32Array(nx * ny * 3);
92 geo.setAttribute("color", new THREE.BufferAttribute(colors, 3));
93 const mat = new THREE.MeshStandardMaterial({ vertexColors: true, side: THREE.DoubleSide, metalness: 0.1, roughness: 0.7 });
94 mesh = new THREE.Mesh(geo, mat);
95 scene.add(mesh);
96 // a thin frame at rest height for reference
97 const edges = new THREE.EdgesGeometry(new THREE.PlaneGeometry(Lx, Ly, 1, 1));
98 const frameLine = new THREE.LineSegments(edges, new THREE.LineBasicMaterial({ color: dark ? 0x555555 : 0xbbbbbb }));
99 mesh.add(frameLine);
100 // strike marker
101 const marker = new THREE.Mesh(new THREE.SphereGeometry(0.004, 12, 12), new THREE.MeshBasicMaterial({ color: 0xd04040 }));
102 marker.position.set(0.09144 - Lx / 2, 0.10668 - Ly / 2, 0.004);
103 mesh.add(marker);
106function updateSurface() {
107 if (!field || !mesh) return;
7141e28Add vonkarman-modal submission for plate-strike-nl-v1; viewer removes rigid motionJeremy Magland 108 const { u, nx, ny, x, y, plane, xm, ym } = field;
109 const rigidOff = derigid.checked;
110 const umax = rigidOff ? field.emax : field.umax;
112 const col = mesh.geometry.attributes.color;
113 const scale = umax > 0 ? (0.03 * Math.pow(10, parseFloat(exag.value)) / umax) * 0.1 : 0; // exaggerated height
114 const base = frame * nx * ny;
7141e28Add vonkarman-modal submission for plate-strike-nl-v1; viewer removes rigid motionJeremy Magland 115 const c0 = plane[3 * frame], gx = plane[3 * frame + 1], gy = plane[3 * frame + 2];
c689df2Add kirchhoff-bfs submission for plate-strike-v1 (meshes 4 to 48), field export via LFS, and this repository's site with a 3D field viewerJeremy Magland 116 // PlaneGeometry vertices run row by row from +y (top) to -y; row r corresponds to y index (ny-1-r)
117 for (let r = 0; r < ny; r++) {
118 const j = ny - 1 - r;
119 for (let i = 0; i < nx; i++) {
121 if (rigidOff) v -= c0 + gx * (x[i] - xm) + gy * (y[j] - ym);
123 const z = v * scale;
124 pos.setZ(k, z);
125 const s = umax > 0 ? Math.max(-1, Math.min(1, v / umax)) : 0;
126 // blue (negative) to white to red (positive)
127 col.setXYZ(k, s > 0 ? 1 : 1 + s * 0.8, 1 - Math.abs(s) * 0.7, s < 0 ? 1 : 1 - s * 0.8);
128 }
129 }
130 pos.needsUpdate = true;
131 col.needsUpdate = true;
132 mesh.geometry.computeVertexNormals();
133 timeSlider.value = String(frame);
134 timeLabel.textContent = `${(field.t[frame] * 1e3).toFixed(0)} ms`;
137function render() { renderer.render(scene, camera); }
138controls.addEventListener("change", render);
140async function loadField(path) {
141 status.textContent = `Loading ${path} (this may take a while, the file is large)…`;
142 playing = false;
143 playBtn.textContent = "Play";
144 try {
145 const { FS } = await h5wasm.ready;
146 const resp = await fetch(path);
147 const buf = new Uint8Array(await resp.arrayBuffer());
148 if (buf.length < 200 && new TextDecoder().decode(buf).startsWith("version https://git-lfs")) {
149 status.textContent = `${path} is a git LFS pointer; the object was not published with this site.`;
150 return;
151 }
152 const name = "current.h5";
153 try { FS.unlink(name); } catch (_) {}
154 FS.writeFile(name, buf);
155 const file = new h5wasm.File(name, "r");
156 const x = Float64Array.from(file.get("x").value);
157 const y = Float64Array.from(file.get("y").value);
158 const t = Float64Array.from(file.get("t").value);
159 const u = Float32Array.from(file.get("u").value);
160 file.close();
7141e28Add vonkarman-modal submission for plate-strike-nl-v1; viewer removes rigid motionJeremy Magland 161 // best-fit plane per frame (the free plate's rigid translation and rotations), so that the
162 // elastic deformation can be shown on its own
163 const nx = x.length, ny = y.length, nt = t.length;
164 const xm = x.reduce((a, b) => a + b, 0) / nx, ym = y.reduce((a, b) => a + b, 0) / ny;
165 let sxx = 0, syy = 0;
166 for (let i = 0; i < nx; i++) sxx += (x[i] - xm) ** 2;
167 for (let j = 0; j < ny; j++) syy += (y[j] - ym) ** 2;
168 sxx *= ny; syy *= nx;
169 const plane = new Float64Array(nt * 3); // c, gx, gy per frame
170 for (let k = 0; k < nt; k++) {
171 let s0 = 0, sx = 0, sy = 0;
172 const base = k * nx * ny;
173 for (let j = 0; j < ny; j++) for (let i = 0; i < nx; i++) {
174 const v = u[base + j * nx + i];
175 s0 += v; sx += v * (x[i] - xm); sy += v * (y[j] - ym);
176 }
177 plane[3 * k] = s0 / (nx * ny); plane[3 * k + 1] = sx / sxx; plane[3 * k + 2] = sy / syy;
178 }
179 let umax = 0, emax = 0;
180 for (let k = 0; k < nt; k++) {
181 const base = k * nx * ny;
182 for (let j = 0; j < ny; j++) for (let i = 0; i < nx; i++) {
183 const v = u[base + j * nx + i];
184 const e = v - plane[3 * k] - plane[3 * k + 1] * (x[i] - xm) - plane[3 * k + 2] * (y[j] - ym);
185 if (Math.abs(v) > umax) umax = Math.abs(v);
186 if (Math.abs(e) > emax) emax = Math.abs(e);
187 }
188 }
189 field = { x, y, t, u, nx, ny, nt, umax, emax, plane, xm, ym };
191 frame = 0;
192 simTime = 0;
193 buildMesh();
194 updateSurface();
195 render();
7141e28Add vonkarman-modal submission for plate-strike-nl-v1; viewer removes rigid motionJeremy Magland 196 status.textContent = `${path}: ${field.nx} × ${field.ny} points × ${field.nt} frames, max |u| = ${(umax * 1e3).toFixed(2)} mm including rigid motion, ${(emax * 1e3).toFixed(3)} mm elastic`;
198 status.textContent = `Could not load ${path}: ${e}`;
199 }
202function tick(ts) {
203 if (!playing || !field) return;
204 if (lastTs !== null) {
205 const factor = Math.pow(10, parseFloat(speed.value));
206 simTime += ((ts - lastTs) / 1000) * factor;
207 const tEnd = field.t[field.nt - 1];
208 if (simTime > tEnd) simTime = 0;
209 const dt = field.t[1] - field.t[0];
210 frame = Math.min(field.nt - 1, Math.round(simTime / dt));
211 updateSurface();
212 render();
213 }
214 lastTs = ts;
215 requestAnimationFrame(tick);
218playBtn.addEventListener("click", () => {
219 playing = !playing;
220 playBtn.textContent = playing ? "Pause" : "Play";
221 lastTs = null;
222 if (playing) requestAnimationFrame(tick);
223});
224timeSlider.addEventListener("input", () => {
225 if (!field) return;
226 frame = parseInt(timeSlider.value, 10);
227 simTime = field.t[frame];
228 updateSurface();
229 render();
230});
231const updSpeed = () => { speedLabel.textContent = `${Math.pow(10, parseFloat(speed.value)).toPrecision(2)} × real time`; };
232const updExag = () => { exagLabel.textContent = `×${Math.pow(10, parseFloat(exag.value)).toPrecision(2)}`; updateSurface(); render(); };
233speed.addEventListener("input", updSpeed);
234exag.addEventListener("input", updExag);
7141e28Add vonkarman-modal submission for plate-strike-nl-v1; viewer removes rigid motionJeremy Magland 235derigid.addEventListener("change", () => { updateSurface(); render(); });
237exagLabel.textContent = `×${Math.pow(10, parseFloat(exag.value)).toPrecision(2)}`;
238select.addEventListener("change", () => loadField(select.value));
240for (const f of fieldSolutions) {
241 const o = document.createElement("option");
242 o.value = f.path;
243 o.textContent = f.label;
244 select.appendChild(o);
246render();
247if (fieldSolutions.length) loadField(fieldSolutions[0].path);
248else status.textContent = "No solution in this repository exports a displacement field that is published with this site.";
↑↓ move↵openescclose