| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167 |
- import { startViewer, stopViewer, recenter, setJoystick } from './viewer.js';
- const STAGES = [
- ['frames', 'Klatki z wideo'],
- ['colmap', 'Pozycje kamer (COLMAP)'],
- ['reconstruct', 'Rekonstrukcja 3D (GenRecon)'],
- ['glb', 'Składanie sceny (GLB)'],
- ];
- const $ = (id) => document.getElementById(id);
- let poll = null;
- function show(view) {
- for (const v of document.querySelectorAll('.view')) v.classList.remove('active');
- $(view).classList.add('active');
- }
- function buildStages() {
- $('stages').innerHTML = STAGES
- .map(([k, label]) => `<li data-stage="${k}"><span class="dot"></span>${label}</li>`).join('');
- }
- function updateStages(current, status) {
- const order = STAGES.map((s) => s[0]);
- const idx = order.indexOf(current);
- document.querySelectorAll('#stages li').forEach((li, i) => {
- li.classList.toggle('done', status === 'done' || i < idx);
- li.classList.toggle('active', status !== 'done' && i === idx);
- });
- }
- // The reconstruction runs entirely server-side (a background worker persists
- // each job to disk). The client is JUST A VIEW: it remembers the active job id
- // (URL + localStorage) so a reload / reconnect / re-open resumes the SAME job,
- // and its polling shrugs off transient network drops instead of freezing.
- const LAST_JOB_KEY = 'genrecon:lastJob';
- let currentJob = null;
- function rememberJob(id) {
- currentJob = id;
- try { localStorage.setItem(LAST_JOB_KEY, id); } catch { /* private mode */ }
- const u = new URL(location.href); u.searchParams.set('job', id); history.replaceState(null, '', u);
- }
- function forgetJob() {
- currentJob = null;
- try { localStorage.removeItem(LAST_JOB_KEY); } catch { /* private mode */ }
- const u = new URL(location.href); u.searchParams.delete('job'); history.replaceState(null, '', u);
- }
- function stopPolling() { if (poll) { clearInterval(poll); poll = null; } }
- function startPolling(id) {
- rememberJob(id);
- stopPolling();
- buildStages(); show('view-progress');
- poll = setInterval(() => refresh(id), 2000);
- refresh(id);
- }
- async function refresh(id) {
- let st;
- try {
- const r = await fetch(`/api/jobs/${id}`);
- if (r.status === 404) { // job unknown/expired → back to upload
- stopPolling(); forgetJob(); show('view-upload'); return;
- }
- st = await r.json();
- } catch { return; } // transient blip (reconnect etc.) → retry next tick, never freeze
- $('bar-fill').style.width = (st.progress || 0) + '%';
- $('progress-msg').textContent = st.message || st.status || '';
- $('progress-msg').classList.toggle('error', st.status === 'error');
- updateStages(st.stage, st.status);
- try {
- const log = await (await fetch(`/api/jobs/${id}/log`)).text();
- const el = $('log'); el.textContent = log; el.scrollTop = el.scrollHeight;
- } catch { /* no log yet */ }
- if (st.status === 'done') {
- stopPolling();
- openViewer(`/api/jobs/${id}/scene.glb`);
- } else if (st.status === 'error') {
- stopPolling();
- $('progress-msg').textContent = '⚠ ' + (st.error || 'błąd rekonstrukcji');
- }
- }
- async function upload(file) {
- if (!file) return;
- buildStages();
- $('bar-fill').style.width = '0'; $('progress-msg').textContent = 'Wysyłanie filmu…'; $('log').textContent = '';
- show('view-progress');
- const fd = new FormData(); fd.append('video', file);
- let res;
- try { res = await (await fetch('/api/jobs', { method: 'POST', body: fd })).json(); }
- catch (e) { $('progress-msg').classList.add('error'); $('progress-msg').textContent = 'Nie udało się wysłać: ' + e; return; }
- if (res.error) { $('progress-msg').classList.add('error'); $('progress-msg').textContent = res.error; return; }
- // Upload done → hand off to the durable server-side job; the client is now just a view.
- startPolling(res.id);
- }
- function openViewer(url) {
- show('view-viewer');
- document.body.classList.toggle('touch', matchMedia('(pointer: coarse)').matches);
- startViewer(url).catch((e) => {
- show('view-upload');
- alert('Nie udało się załadować sceny 3D: ' + e);
- });
- }
- function backToUpload() {
- stopPolling();
- forgetJob();
- stopViewer();
- show('view-upload');
- }
- // --- mobile joystick ---
- function wireJoystick() {
- const stick = $('joystick'), knob = $('joystick-knob');
- let active = null, cx = 0, cy = 0, R = 45;
- const set = (dx, dy) => {
- const len = Math.hypot(dx, dy) || 1, cl = Math.min(len, R);
- dx = dx / len * cl; dy = dy / len * cl;
- knob.style.transform = `translate(${dx}px,${dy}px)`;
- setJoystick(dx / R, -dy / R); // up = forward
- };
- stick.addEventListener('pointerdown', (e) => {
- active = e.pointerId; const r = stick.getBoundingClientRect();
- cx = r.left + r.width / 2; cy = r.top + r.height / 2;
- stick.setPointerCapture(e.pointerId); set(e.clientX - cx, e.clientY - cy);
- });
- stick.addEventListener('pointermove', (e) => { if (e.pointerId === active) set(e.clientX - cx, e.clientY - cy); });
- const end = (e) => { if (e.pointerId === active) { active = null; knob.style.transform = ''; setJoystick(0, 0); } };
- stick.addEventListener('pointerup', end);
- stick.addEventListener('pointercancel', end);
- }
- function init() {
- const drop = $('drop'), input = $('file-input');
- input.addEventListener('change', () => upload(input.files[0]));
- ['dragenter', 'dragover'].forEach((ev) => drop.addEventListener(ev, (e) => { e.preventDefault(); drop.classList.add('drag'); }));
- ['dragleave', 'drop'].forEach((ev) => drop.addEventListener(ev, (e) => { e.preventDefault(); drop.classList.remove('drag'); }));
- drop.addEventListener('drop', (e) => upload(e.dataTransfer.files[0]));
- $('btn-demo').addEventListener('click', () => openViewer('./demo.glb'));
- $('btn-cancel').addEventListener('click', backToUpload);
- $('btn-new').addEventListener('click', backToUpload);
- $('btn-recenter').addEventListener('click', recenter);
- wireJoystick();
- if ('serviceWorker' in navigator) navigator.serviceWorker.register('./sw.js').catch(() => {});
- // Resume the active job on load — from the URL (?job=, shareable) or, failing
- // that, from localStorage. So closing the tab, losing signal, or reopening the
- // app hours later drops you right back onto the still-running / finished scan.
- let resumeId = new URLSearchParams(location.search).get('job');
- if (!resumeId) { try { resumeId = localStorage.getItem(LAST_JOB_KEY); } catch { /* private mode */ } }
- if (resumeId) startPolling(resumeId);
- // Mobile browsers freeze timers on a backgrounded tab; re-sync the moment the
- // tab is visible / the network is back, instead of waiting for the next tick.
- const resync = () => {
- if (!currentJob || document.hidden) return;
- if ($('view-viewer').classList.contains('active')) return; // don't reload the walkthrough mid-explore
- refresh(currentJob);
- };
- document.addEventListener('visibilitychange', resync);
- window.addEventListener('online', resync);
- window.addEventListener('focus', resync);
- }
- init();
|