auto-si-webgl2 / app.js
axonis22's picture
Upload Auto-SI WebGL2 root files
2e8ea5b verified
Raw History Blame Contribute Delete
32.1 kB
(function(){
"use strict";
var D = window.AUTOSI;
var KEY = "autosi.v0.5";
var state = load();
function load(){
var s = {};
try { s = JSON.parse(localStorage.getItem(KEY)) || {}; } catch(e){}
var on = s.on || {};
D.groups.forEach(function(g){ if(!(g.id in on)) on[g.id] = true; });
return { on:on, mode:s.mode||"filter", autoSI:!!s.autoSI, slider:s.slider||32, notes:s.notes||{}, grid:s.grid!==false, light:s.light!==false, wire:!!s.wire, lookPanel:s.lookPanel!==false };
}
function save(){ try{ localStorage.setItem(KEY, JSON.stringify(state)); }catch(e){} }
function el(tag, cls, text){
var e = document.createElement(tag);
if(cls) e.className = cls;
if(text != null) e.textContent = text;
return e;
}
function $(id){ return document.getElementById(id); }
var gname = {}; D.groups.forEach(function(g){ gname[g.id] = g.name; });
/* switches */
function buildSwitches(){
var host = $("switches"); host.textContent = "";
D.groups.forEach(function(g){
var lab = el("label","switch");
var cb = el("input"); cb.type = "checkbox"; cb.checked = !!state.on[g.id]; cb.dataset.g = g.id;
cb.addEventListener("change", function(){ state.on[g.id] = cb.checked; save(); render(); });
var sl = el("span","slider");
var t = el("span","lbl", g.name); t.appendChild(el("small",null,g.hint));
lab.appendChild(cb); lab.appendChild(sl); lab.appendChild(t);
host.appendChild(lab);
});
}
function setAll(v){ D.groups.forEach(function(g){ state.on[g.id] = v; }); save(); buildSwitches(); render(); }
function matches(p){ return p.groups.some(function(g){ return state.on[g]; }); }
/* timeline */
function fmtNum(p){ return p.side ? "29b" : String(p.n); }
function renderTimeline(){
var host = $("timeline"); host.textContent = "";
var shownSet = {}, totalSet = {}, era = null;
D.phases.forEach(function(p){
var m = matches(p);
if(!p.side){ totalSet[p.n] = 1; if(m) shownSet[p.n] = 1; }
if(!m && state.mode === "filter") return;
if(!p.side && p.era !== era){ era = p.era; host.appendChild(el("h2","era",era)); }
var c = el("article","card" + (p.side?" proto":"") + (p.sub?" sub":"") + (!m?" dim":""));
var num = el("div","num"); num.appendChild(el("b",null,fmtNum(p)));
num.appendChild(el("span",null, p.sub ? p.sub : (p.side ? "side" : (p.n>=30 ? "Engine" : "Phase"))));
var b = el("div","body");
b.appendChild(el("h3",null,p.title));
b.appendChild(el("div","date", p.date + " Sydney time (AEST)" + (p.by ? " | " + p.by : "")));
b.appendChild(el("p",null,p.plain));
var chips = el("div","chips");
p.groups.forEach(function(g){ chips.appendChild(el("span","chip"+(state.on[g]?" on":""), gname[g])); });
b.appendChild(chips);
var det = el("details"); det.appendChild(el("summary",null,"Source files and modules (" + p.src.length + ")"));
var ul = el("ul","src"); p.src.forEach(function(s){ ul.appendChild(el("li",null,s)); });
det.appendChild(ul); b.appendChild(det);
if((p.n>=29 && !p.side && p.sub) || p.n>=30){
var a = el("div","actions");
if(p.port){
var l = el("a","btn link","Open local page (port " + p.port + ")");
l.href = "http://localhost:" + p.port + "/"; l.target = "_blank"; l.rel = "noopener";
a.appendChild(l);
}
if(p.hf){
var h = el("a","btn link","Open Hugging Face Space");
h.href = p.hf; h.target = "_blank"; h.rel = "noopener"; a.appendChild(h);
}
a.appendChild(el("span","fine", (p.portNote||"") + (p.port ? ". Works only on a computer that is running that engine's server." : "") + (!p.hf ? " No verified Hugging Face Space." : "")));
b.appendChild(a);
}
c.appendChild(num); c.appendChild(b); host.appendChild(c);
});
if(!host.firstChild) host.appendChild(el("p","fine","No groups are switched on. Switch at least one group on."));
var shown = Object.keys(shownSet).length, total = Object.keys(totalSet).length;
$("summary").textContent = shown + " of " + total + " numbered phases match the groups switched on" +
(state.mode==="filter" ? " (filter mode)." : " (highlight mode: others are dimmed).") +
" 29b is an unnumbered side prototype.";
}
/* cumulative */
function phaseLabel(n){ return n >= 30 ? "Engine " + n : "Phase " + n; }
function renderCum(){
var n = state.slider;
$("phaseSlider").value = n; $("phaseOut").textContent = n;
var ph = D.phases.filter(function(p){ return p.n === n && !p.side; });
$("phaseName").textContent = ph.map(function(p){ return phaseLabel(n) + (p.sub?" ("+p.sub+")":"") + ": " + p.title + " (" + p.date.slice(0,10) + ")"; }).join(" | ");
var host = $("cumList"); host.textContent = "";
var on = 0, later = 0;
D.groups.forEach(function(g){
if(!state.on[g.id]) return;
var fs = D.features.filter(function(f){ return f.group === g.id; });
if(!fs.length) return;
var now = fs.filter(function(f){ return f.at <= n; });
host.appendChild(el("div","grp", g.name + " (" + now.length + " of " + fs.length + " by phase " + n + ")"));
fs.forEach(function(f){
var isOn = f.at <= n; if(isOn) on++; else later++;
var r = el("div","feat" + (isOn ? "" : " later"));
r.appendChild(el("div","at","P" + f.at));
var d = el("div"); d.appendChild(el("div",null,f.name + (f.cfg ? " [cfg: " + f.cfg + ", default " + (f.def?"on":"off") + "]" : "")));
d.appendChild(el("div","d", f.desc + (isOn ? "" : " (not yet introduced)")));
r.appendChild(d); host.appendChild(r);
});
});
$("cumSummary").textContent = on + " features available by phase " + n + "; " + later + " arrive later (greyed). Only groups switched on are listed.";
}
/* models panel */
function human(b){ if(b==null) return "unknown size"; if(b<1024) return b+" B"; if(b<1048576) return (b/1024).toFixed(1)+" KB"; return (b/1048576).toFixed(1)+" MB"; }
function typeOf(name){
var m = /\.([a-z0-9]+)$/i.exec(name||""); var e = m ? m[1].toLowerCase() : "";
return D.modelTypes.find(function(t){ return t.ext.indexOf("."+e) >= 0 || (e==="gltf" && t.id==="glb"); }) || null;
}
function template(name, bytes, t){
var kind = t ? t.name : "an unrecognised type";
var scale = bytes==null ? "of unknown size" : bytes < 1048576 ? "small (under 1 MB)" : bytes < 20971520 ? "medium (1 to 20 MB)" : "large (over 20 MB), so check texture and memory use first";
var extra = t && t.id==="3ds" ? " This format is local only and is not supported in the published Space." : "";
return "\"" + name + "\" is " + (/^[AEIOUF]/.test(kind) ? "an " : "a ") + kind + " file, " + human(bytes) + ", which is " + scale + ". " + (t ? t.plain : "Auto-SI does not know this type.") + extra;
}
function tplBox(text){
var b = el("div","tpl"); b.appendChild(el("span","label","Template description. Generated from the file's own data (or its name, type and size where the file is not loaded). No SI model was called. Customised looks are viewer-only and do not change the file."));
b.appendChild(el("span",null,text)); return b;
}
function renderModels(){
var th = $("typeList"); th.textContent = "";
D.modelTypes.forEach(function(t){
var c = el("div","card");
c.appendChild(el("span","tag" + (t.id==="3ds"?" warn":""), t.status));
c.appendChild(el("h3",null,t.name + " (" + t.ext + ")"));
c.appendChild(el("p",null,t.plain));
c.appendChild(el("div","fine","First seen: " + t.firstSeen));
c.appendChild(el("div","fine",t.note));
if(t.autosi) c.appendChild(el("p","fine","In Auto-SI v0.5: " + t.autosi));
if(t.next) c.appendChild(el("p","fine","Coming next: " + t.next));
th.appendChild(c);
});
var sh = $("sampleList"); sh.textContent = "";
D.samples.forEach(function(s){
var c = el("div","card");
c.appendChild(el("h3",null,s.file));
c.appendChild(el("div","fine","Source: " + s.source));
var a = el("a",null,s.url); a.href = s.url; a.target="_blank"; a.rel="noopener"; c.appendChild(a);
c.appendChild(el("p",null,"Licence: " + s.licence));
c.appendChild(el("div","fine","Used in: " + s.usedIn));
c.appendChild(el("div","fine","Verification: " + s.verified));
c.appendChild(el("div","fine","Referenced only: not bundled with Auto-SI."));
if(state.autoSI) c.appendChild(tplBox(template(s.file, s.sizeBytes, typeOf(s.type==="fbx"?"x.fbx":"x.glb"))));
sh.appendChild(c);
});
}
/* model chooser (v0.2, look panel v0.3, Muse raw WebGL renderer v0.4, WebGL2 engine build v0.5) */
var cur = null; /* {kind:"library", entry} or {kind:"file", files:[File]} */
var viewerOK = false, viewerTried = false;
function n1(x){ return (Math.round(x*1000)/1000).toString(); }
function plural(n, one, many){ return n.toLocaleString("en-AU") + " " + (n===1 ? one : (many||one+"s")); }
function viewer(){ return window.AutoSIViewer || null; }
function setStatus(msg, isErr){
var b = $("viewStatus"); b.textContent = msg || ""; b.className = "viewstatus" + (isErr ? " err" : "");
b.setAttribute("role", isErr ? "alert" : "status");
}
function ensureViewer(){
var v = viewer();
if(v && v.ready){ viewerOK = true; setTimeout(v.resize, 0); return; }
if(v && !viewerTried){ viewerTried = true; viewerOK = v.init($("viewHost")); if(viewerOK){ wireViewer(); } else { setStatus("The 3D preview could not start: this browser or device has no usable WebGL. Everything else in Auto-SI still works.", true); } return; }
if(!v && !viewerTried){
setStatus("Starting the 3D preview...");
var tries = 0, t = setInterval(function(){
if(viewer()){ clearInterval(t); ensureViewer(); if(cur) reloadCurrent(); }
else if(++tries > 40){ clearInterval(t); setStatus("The 3D preview did not start. Its scripts (parsers.js, viewer.js or engine/gl2) failed to load. Details are in the browser console.", true); }
}, 100);
}
}
/* renderer picker: Auto / WebGL 2 / WebGL 1. The choice is kept in the address (?gl=) and in this browser, then the page reloads. */
function wireRenderer(v){
var sel = $("glSel"), out = $("glInfo"), ri = v.renderInfo || {};
if(out) out.textContent = ri.version ? "Drawing with WebGL " + ri.version + (ri.fallbackReason ? " (" + ri.fallbackReason + ")" : "") : "";
if(!sel) return;
sel.value = ri.requested === "1" || ri.requested === "2" ? ri.requested : "auto";
sel.addEventListener("change", function(){
var val = sel.value;
try{ if(window.MuseGL2) window.MuseGL2.savePreference(val); }catch(e){}
var u = new URL(location.href); u.searchParams.set("gl", val); location.href = u.toString();
});
}
function wireViewer(){
var v = viewer();
v.setGrid(state.grid); v.setLight(state.light); v.setWire(state.wire);
wireRenderer(v);
v.onEvent(function(type, d){
if(type==="look"){ syncLookPanel(d); return; }
if(type==="loading") setStatus("Loading " + d + "...");
else if(type==="error") setStatus(d, true);
else if(type==="loaded"){ setStatus("Loaded. Drag to orbit, scroll to zoom, right-drag or Shift-drag to pan." + (d.notes && d.notes.length ? " Note: " + d.notes.join(" ") : ""), false); syncLookPanel({look:v.getLook(), source:"reset"}); }
updateLookAvail();
renderDetails();
});
}
/* Customise look panel (v0.3). Viewer-only: it never changes the model file. */
var LOOKCTL = [
{sec:"Preset"}, {preset:true},
{sec:"Colour"},
{k:"tint", t:"color", label:"Colour tint"},
{k:"tintAmount", t:"range", min:0, max:100, step:1, scale:100, unit:"%", label:"Tint strength"},
{k:"glow", t:"range", min:0, max:200, step:5, scale:100, unit:"%", label:"Glow (uses tint colour)"},
{k:"plain", t:"check", label:"Flat colour (ignore pictures and vertex colours)"},
{sec:"Light"},
{k:"exposure", t:"range", min:0.2, max:3, step:0.05, unit:"x", label:"Brightness (exposure)"},
{k:"lightStrength", t:"range", min:0, max:3, step:0.05, unit:"x", label:"Light strength"},
{k:"lightAz", t:"range", min:0, max:360, step:1, unit:"\u00b0", label:"Light rotation"},
{k:"lightEl", t:"range", min:5, max:90, step:1, unit:"\u00b0", label:"Light height"},
{sec:"Surface"},
{k:"rough", on:"roughOn", t:"over", min:0, max:1, step:0.01, label:"Roughness"},
{k:"metal", on:"metalOn", t:"over", min:0, max:1, step:0.01, label:"Metalness"},
{k:"wire", t:"check", label:"Wireframe"},
{sec:"Background"},
{k:"bg", t:"color", label:"Background colour"},
{k:"transparent", t:"check", label:"Transparent background"},
{sec:"Camera"},
{k:"autoRotate", t:"range", min:0, max:10, step:0.5, unit:"", label:"Auto-rotate speed (0 = off)"},
{k:"fov", t:"range", min:20, max:100, step:1, unit:"\u00b0", label:"Field of view"},
{sec:"Ground"},
{k:"grid", t:"check", label:"Ground grid"},
{k:"shadow", t:"check", label:"Ground shadow"}
];
var lookCtl = {}, lookSel = null, lookStatus = null;
function lookSet(part){
var v = viewer(); if(!v || !v.ready) return;
try { v.setLook(part, "panel"); lookMsg(""); } catch(e){ lookMsg(e.message, true); }
}
function lookMsg(msg, isErr){ if(!lookStatus) return; lookStatus.textContent = msg || ""; lookStatus.className = "status" + (isErr ? " err" : ""); lookStatus.setAttribute("role", isErr ? "alert" : "status"); }
function buildLookPanel(){
var P = $("lookPanel"); P.textContent = "";
P.appendChild(el("h3", null, "Customise look"));
P.appendChild(el("div", "fine", "Viewer-only. These settings never change the model file. Reset restores the exact loaded look."));
LOOKCTL.forEach(function(c){
if(c.sec){ P.appendChild(el("h4", null, c.sec)); return; }
if(c.preset){
lookSel = el("select"); lookSel.id = "lk-preset"; lookSel.setAttribute("aria-label", "Look preset");
[["original","Original"],["clay","Clay"],["neon","Neon"],["night","Night"],["custom","Custom"]].forEach(function(p){ var o = el("option", null, p[1]); o.value = p[0]; lookSel.appendChild(o); });
lookSel.addEventListener("change", function(){
var v = viewer(); if(!v || !v.ready || lookSel.value === "custom") return;
try { v.applyPreset(lookSel.value); lookMsg(""); } catch(e){ lookMsg(e.message, true); }
});
P.appendChild(lookSel); return;
}
var row = el("label", "lk" + (c.t === "check" ? " chk" : ""));
var id = "lk-" + c.k;
if(c.t === "check"){
var cb = el("input"); cb.type = "checkbox"; cb.id = id;
cb.addEventListener("change", function(){ var p = {}; p[c.k] = cb.checked; lookSet(p); });
row.appendChild(cb); row.appendChild(el("span", "t", c.label));
lookCtl[c.k] = {input:cb, kind:"check"};
} else if(c.t === "color"){
row.appendChild(el("span", "t", c.label));
var ci = el("input"); ci.type = "color"; ci.id = id; ci.setAttribute("aria-label", c.label);
ci.addEventListener("input", function(){ var p = {}; p[c.k] = ci.value; lookSet(p); });
row.appendChild(ci); lookCtl[c.k] = {input:ci, kind:"color"};
} else if(c.t === "range"){
row.appendChild(el("span", "t", c.label));
var ri = el("input"); ri.type = "range"; ri.id = id; ri.min = c.min; ri.max = c.max; ri.step = c.step; ri.setAttribute("aria-label", c.label);
var out = el("output"); out.htmlFor = id;
ri.addEventListener("input", function(){ var p = {}; p[c.k] = (+ri.value) / (c.scale || 1); lookSet(p); });
row.appendChild(ri); row.appendChild(out); lookCtl[c.k] = {input:ri, out:out, kind:"range", c:c};
} else if(c.t === "over"){
/* roughness or metalness: a 'use original' checkbox plus an override slider */
var wrap = el("div"); wrap.style.cssText = "margin:4px 0";
var r1 = el("label", "lk chk"); var oc = el("input"); oc.type = "checkbox"; oc.id = "lk-" + c.on;
oc.addEventListener("change", function(){ var p = {}; p[c.on] = !oc.checked; lookSet(p); });
r1.appendChild(oc); r1.appendChild(el("span", "t", "Use original " + c.label.toLowerCase()));
var r2 = el("label", "lk"); r2.appendChild(el("span", "t", c.label + " override"));
var si = el("input"); si.type = "range"; si.id = id; si.min = c.min; si.max = c.max; si.step = c.step; si.setAttribute("aria-label", c.label + " override");
var so = el("output"); so.htmlFor = id;
si.addEventListener("input", function(){ var p = {}; p[c.k] = +si.value; p[c.on] = true; lookSet(p); });
r2.appendChild(si); r2.appendChild(so); wrap.appendChild(r1); wrap.appendChild(r2); P.appendChild(wrap);
lookCtl[c.k] = {input:si, out:so, kind:"over", c:c}; lookCtl[c.on] = {input:oc, kind:"overOn"};
return;
}
P.appendChild(row);
});
var rowb = el("div", "lkrow");
var rb = el("button", "btn", "Reset"); rb.type = "button"; rb.id = "lk-reset"; rb.title = "Restore the exact loaded look";
rb.addEventListener("click", function(){ var v = viewer(); if(v && v.ready){ v.resetLook(); lookMsg("Restored the loaded look."); } });
var sb = el("button", "btn", "Save look"); sb.type = "button"; sb.id = "lk-save"; sb.addEventListener("click", saveLook);
var lb = el("button", "btn", "Load look"); lb.type = "button"; lb.id = "lk-load";
var fi = el("input"); fi.type = "file"; fi.accept = ".json,application/json"; fi.id = "lk-file"; fi.hidden = true; fi.setAttribute("aria-label", "Look file (.json)");
lb.addEventListener("click", function(){ fi.click(); });
fi.addEventListener("change", function(){ loadLookFile(fi.files && fi.files[0]); fi.value = ""; });
rowb.appendChild(rb); rowb.appendChild(sb); rowb.appendChild(lb); rowb.appendChild(fi); P.appendChild(rowb);
lookStatus = el("div", "status"); lookStatus.setAttribute("role", "status"); P.appendChild(lookStatus);
P.appendChild(el("div", "fine", "Look files are small JSON files saved and read on this device only. Shortcut: press H to hide or show this panel."));
}
function fmtLook(c, val){
var x = c.scale ? val * c.scale : val;
return (c.step < 1 ? (Math.round(x * 100) / 100) : Math.round(x)) + (c.unit || "");
}
function syncLookPanel(d){
var L = d.look;
state.grid = L.grid; state.wire = L.wire;
$("gridBtn").setAttribute("aria-pressed", String(!!L.grid)); $("wireBtn").setAttribute("aria-pressed", String(!!L.wire)); save();
Object.keys(lookCtl).forEach(function(k){
var c = lookCtl[k], val = L[k];
if(c.kind === "check") c.input.checked = !!val;
else if(c.kind === "color") c.input.value = val;
else if(c.kind === "range" || c.kind === "over"){
c.input.value = c.c.scale ? val * c.c.scale : val;
c.out.textContent = c.kind === "over" ? (L[c.c.on] ? fmtLook(c.c, val) : "original") : fmtLook(c.c, val);
if(c.kind === "over") c.input.disabled = !L[c.c.on];
} else if(c.kind === "overOn") c.input.checked = !val;
});
var src = d.source || "";
if(lookSel){
if(src.indexOf("preset:") === 0) lookSel.value = src.slice(7);
else if(src === "reset") lookSel.value = "original";
else if(src === "panel" || src === "file") lookSel.value = "custom";
}
}
function saveLook(){
var v = viewer(); if(!v || !v.ready) return;
var data = {autosi:"look", version:1, app:"Auto-SI 0.5", note:"Viewer-only look settings. Contains no model data and never changes a model file.", look:v.getLook()};
try {
var blob = new Blob([JSON.stringify(data, null, 2) + "\n"], {type:"application/json"});
var url = URL.createObjectURL(blob), a = document.createElement("a");
a.href = url; a.download = "autosi-look.json"; document.body.appendChild(a); a.click(); a.remove();
setTimeout(function(){ URL.revokeObjectURL(url); }, 5000);
lookMsg("Saved autosi-look.json (see your Downloads folder). Local only.");
} catch(e){ lookMsg("Could not save the look file: " + e.message, true); }
}
function loadLookFile(f){
if(!f) return;
var v = viewer(); if(!v || !v.ready) return;
if(f.size > 100000){ lookMsg("That file is too big to be a Auto-SI look file (limit 100 KB).", true); return; }
f.text().then(function(t){
var o; try { o = JSON.parse(t); } catch(e){ throw new Error("That file is not valid JSON."); }
if(!o || o.autosi !== "look" || !o.look) throw new Error("That file is not an Auto-SI look file.");
v.setLook(o.look, "file");
lookMsg("Loaded look from " + f.name + ".");
}).catch(function(e){ lookMsg(e.message, true); });
}
function updateLookAvail(){
var v = viewer(), has = !!(v && v.ready && v.hasModel && v.hasModel());
var b = $("lookBtn"), p = $("lookPanel");
b.hidden = !has;
var show = has && state.lookPanel;
p.hidden = !show;
b.setAttribute("aria-pressed", String(show));
b.setAttribute("aria-expanded", String(show));
b.textContent = show ? "Hide look panel (H)" : "Customise look (H)";
if(v && v.ready) setTimeout(v.resize, 0);
}
function toggleLookPanel(){
var v = viewer(); if(!v || !v.ready || !v.hasModel()) return;
state.lookPanel = !state.lookPanel; save(); updateLookAvail();
}
document.addEventListener("keydown", function(e){
if(e.key !== "h" && e.key !== "H") return;
if(e.ctrlKey || e.metaKey || e.altKey) return;
var t = e.target;
if(t && (t.isContentEditable || /^(TEXTAREA|SELECT)$/.test(t.tagName) || (t.tagName === "INPUT" && /^(text|number|search|email|url|password)$/i.test(t.type || "text")))) return;
if($("tab-chooser").hidden) return;
var v = viewer(); if(!v || !v.ready || !v.hasModel()) return;
e.preventDefault(); toggleLookPanel();
});
function reloadCurrent(){ if(!cur) return; if(cur.kind==="library") loadLibrary(cur.entry); else loadFiles(cur.files); }
function loadLibrary(e){
cur = {kind:"library", entry:e}; renderChooser(); renderDetails();
var v = viewer(); if(!v || !v.ready){ ensureViewer(); if(!viewerOK) return; v = viewer(); }
var items = [{name:e.file, url:e.file}].concat((e.extra||[]).map(function(u){ return {name:u, url:u}; }));
v.load(items, {library:e.id}).catch(function(){});
}
function loadFiles(files){
files = Array.prototype.slice.call(files||[]);
if(!files.length) return;
var main = files.find(function(f){ var m = /\.([a-z0-9]+)$/i.exec(f.name); return !!m && ["glb","gltf","obj","fbx","3ds"].indexOf(m[1].toLowerCase()) >= 0; }) || files[0];
var rest = files.filter(function(f){ return f !== main; });
cur = {kind:"file", files:files, main:main}; renderChooser(); renderDetails();
var v = viewer(); if(!v || !v.ready){ ensureViewer(); if(!viewerOK) return; v = viewer(); }
v.load([{name:main.name, file:main}].concat(rest.map(function(f){ return {name:f.name, file:f}; })), {}).catch(function(){});
}
function renderChooser(){
var host = $("libList"); host.textContent = "";
D.library.forEach(function(e){
var c = el("div","card lib" + (cur && cur.entry===e ? " sel" : ""));
c.appendChild(el("span","tag", e.type.toUpperCase() + " | " + human(e.bytes)));
c.appendChild(el("h3",null,e.name));
c.appendChild(el("div","fine","Licence: " + e.licence));
c.appendChild(el("p","fine",e.plain));
var b = el("button","btn", cur && cur.entry===e ? "Showing" : "Preview");
b.type = "button"; b.addEventListener("click", function(){ loadLibrary(e); $("viewHost").scrollIntoView({block:"nearest"}); });
c.appendChild(b); host.appendChild(c);
});
}
function scaleWords(b){ return b < 1048576 ? "small (under 1 MB)" : b < 20971520 ? "medium (1 to 20 MB)" : "large (over 20 MB)"; }
function weight(t){ return t < 10000 ? "light" : t < 100000 ? "moderate" : "heavy"; }
function templateFromInfo(i){
var kind = {glb:"GLB (glTF binary)", gltf:"glTF", obj:"OBJ", fbx:"FBX"}[i.type] || i.type.toUpperCase();
var out = [];
out.push("\"" + i.displayName + "\" is " + (/^[AEIOUF]/.test(kind) ? "an " : "a ") + kind + " file, " + human(i.bytes) + " (" + scaleWords(i.bytes) + ").");
out.push("It holds " + plural(i.meshes,"mesh","meshes") + " (separately drawn pieces) made of " + plural(i.triangles,"triangle") + " in total (" + plural(i.vertices,"vertex","vertices") + "), which is a " + weight(i.triangles) + " load for a game engine.");
if(i.materials){
var tys = Object.keys(i.materialTypes).map(function(k){ return i.materialTypes[k] + " x " + k; }).join(", ");
out.push("Surfaces: " + plural(i.materials,"material") + " (" + tys + "), using " + plural(i.textures,"picture (texture)","pictures (textures)") + (i.hasVertexColours ? "; some shapes also carry per-vertex colour" : "") + ".");
} else out.push("Surfaces: no materials were read, so the preview shows plain grey" + (i.hasVertexColours ? " (vertex colours are present)" : "") + ".");
var unit = i.type==="glb"||i.type==="gltf" ? "glTF defines one unit as one metre" : i.type==="fbx" ? "FBX does not fix a unit and often uses centimetres" : "OBJ does not fix a unit";
out.push("Bounding size: " + n1(i.size.x) + " wide x " + n1(i.size.y) + " tall x " + n1(i.size.z) + " deep, in the file's own units (" + unit + ").");
if(i.animations.length){
out.push("Animations: " + plural(i.animations.length,"clip") + " (" + i.animations.map(function(a){ return a.name + ", " + n1(a.seconds) + " s"; }).join("; ") + ")" + (i.bones ? ", driving a skeleton of " + plural(i.bones,"bone") : "") + ".");
} else out.push("Animations: none, so this is a still model" + (i.bones ? " (it does contain " + plural(i.bones,"bone") + ")" : "") + ".");
var gen = {glb:"GLB and glTF are the most widely used formats for sharing 3D models on the web and in games.", gltf:"GLB and glTF are the most widely used formats for sharing 3D models on the web and in games.", obj:"OBJ is a very old plain-text format that stores shape only (no animation).", fbx:"FBX is Autodesk's exchange format for models and animated characters; its units and up-direction vary between exporters."};
if(gen[i.type]) out.push(gen[i.type]);
return out.join(" ");
}
function renderDetails(){
var host = $("detailOut"); host.textContent = "";
if(!cur){ host.appendChild(el("p","fine","Nothing chosen yet. Pick a test model above, or choose your own file.")); syncAnim(null); return; }
var v = viewer(), info = v && v.lastInfo;
var mine = info && ((cur.kind==="library" && info.name===cur.entry.file) || (cur.kind==="file" && info.name===cur.main.name));
var c = el("div","card");
if(cur.kind==="library"){
var e = cur.entry;
c.appendChild(el("span","tag warn","Test only, not part of any release"));
c.appendChild(el("h3",null,e.name));
c.appendChild(el("div","fine","File: " + e.file + " | Type: " + e.type.toUpperCase() + " | Size: " + human(e.bytes)));
c.appendChild(el("p",null,e.plain));
c.appendChild(el("div","fine","Author or credit: " + e.author));
c.appendChild(el("div","fine","Licence: " + e.licence));
c.appendChild(el("div","fine","Credit line: " + e.credit));
var a = el("a",null,e.url); a.href = e.url; a.target = "_blank"; a.rel = "noopener"; c.appendChild(a);
} else {
var f = cur.main, t = typeOf(f.name);
c.appendChild(el("span","tag","Your file, read in this browser only, never uploaded"));
c.appendChild(el("h3",null,f.name));
c.appendChild(el("div","fine","Type: " + (t ? t.name : "unrecognised") + " | Size: " + human(f.size) + (cur.files.length>1 ? " | plus " + (cur.files.length-1) + " side file(s)" : "")));
var k = "file:" + f.name; var n = state.notes[k] || {licence:"",source:""};
[["licence","Licence (your note)"],["source","Source (your note)"]].forEach(function(fl){
c.appendChild(el("div","fine",fl[1]));
var i = el("input"); i.type="text"; i.value = n[fl[0]]; i.maxLength = 200; i.setAttribute("aria-label", fl[1]);
i.addEventListener("input", function(){ n[fl[0]] = i.value; state.notes[k] = n; save(); });
c.appendChild(i);
});
}
if(mine){
c.appendChild(el("div","fine","Read from the loaded file: " + plural(info.meshes,"mesh","meshes") + ", " + plural(info.triangles,"triangle") + ", " + plural(info.materials,"material") + ", " + plural(info.animations.length,"animation") + "."));
if(state.autoSI) c.appendChild(tplBox(templateFromInfo(info)));
else c.appendChild(el("div","fine","Switch on Auto-SI description at the left to see a description built from this file's data."));
} else if(state.autoSI){
c.appendChild(el("div","fine", v && v.lastError ? "No description: the file did not load (see the message above the preview)." : "The description appears once the file has loaded."));
} else c.appendChild(el("div","fine","Switch on Auto-SI description at the left to see a description built from this file's data."));
host.appendChild(c);
syncAnim(mine ? info : null);
}
function syncAnim(info){
var box = $("animBox"), sel = $("animSel");
if(!info || !info.animations.length){ box.hidden = true; return; }
if(sel.dataset.for !== info.name){
sel.textContent = ""; info.animations.forEach(function(a,i){ var o = el("option",null,a.name + " (" + n1(a.seconds) + " s)"); o.value = i; sel.appendChild(o); });
sel.dataset.for = info.name; $("playBtn").textContent = "Play"; $("playBtn").dataset.on = "0";
}
box.hidden = false;
}
function toggleBtn(id, key, fn){
var b = $(id); b.setAttribute("aria-pressed", String(!!state[key]));
b.addEventListener("click", function(){ state[key] = !state[key]; b.setAttribute("aria-pressed", String(state[key])); save(); var v = viewer(); if(v && v.ready) v[fn](state[key]); });
}
/* tabs */
function showTab(id){
document.querySelectorAll(".tabs button").forEach(function(b){ b.setAttribute("aria-selected", String(b.dataset.tab===id)); });
document.querySelectorAll(".tab").forEach(function(s){ s.hidden = (s.id !== "tab-"+id); });
if(location.hash !== "#"+id) history.replaceState(null,"","#"+id);
if(id==="chooser") ensureViewer();
}
function render(){ renderTimeline(); renderCum(); renderModels(); renderChooser(); renderDetails(); }
document.querySelectorAll(".tabs button").forEach(function(b){ b.addEventListener("click", function(){ showTab(b.dataset.tab); }); });
$("allOn").addEventListener("click", function(){ setAll(true); });
$("allOff").addEventListener("click", function(){ setAll(false); });
document.querySelectorAll("input[name=mode]").forEach(function(r){
r.checked = (r.value === state.mode);
r.addEventListener("change", function(){ if(r.checked){ state.mode = r.value; save(); render(); } });
});
$("autoSI").checked = state.autoSI;
$("autoSI").addEventListener("change", function(){ state.autoSI = $("autoSI").checked; save(); render(); });
$("phaseSlider").addEventListener("input", function(){ state.slider = +$("phaseSlider").value; save(); renderCum(); });
toggleBtn("gridBtn","grid","setGrid"); toggleBtn("lightBtn","light","setLight"); toggleBtn("wireBtn","wire","setWire");
$("lookBtn").addEventListener("click", toggleLookPanel);
$("resetBtn").addEventListener("click", function(){ var v = viewer(); if(v && v.ready) v.resetView(); });
$("playBtn").addEventListener("click", function(){
var v = viewer(); if(!v || !v.ready) return;
var on = $("playBtn").dataset.on !== "1";
var res = v.play(+$("animSel").value || 0, on);
$("playBtn").dataset.on = res ? "1" : "0"; $("playBtn").textContent = res ? "Pause" : "Play";
});
$("animSel").addEventListener("change", function(){ var v = viewer(); if(v && v.ready){ v.play(+$("animSel").value, false); v.play(+$("animSel").value, $("playBtn").dataset.on==="1"); } });
$("fileIn").addEventListener("change", function(){ loadFiles($("fileIn").files); });
buildLookPanel(); buildSwitches(); render();
var h = (location.hash||"").slice(1); showTab(["timeline","cumulative","chooser","models","about"].indexOf(h)>=0 ? h : "timeline");
/* PWA */
var deferred = null;
window.addEventListener("beforeinstallprompt", function(e){ e.preventDefault(); deferred = e; $("installBtn").hidden = false; });
$("installBtn").addEventListener("click", function(){ if(deferred){ deferred.prompt(); deferred = null; $("installBtn").hidden = true; } });
if("serviceWorker" in navigator){
navigator.serviceWorker.register("sw.js", {scope:"./"}).then(function(){
$("swState").textContent = "Service worker registered: the app shell is cached for offline use.";
}).catch(function(err){
$("swState").textContent = "Service worker not active (" + err.message + "). It needs http://localhost or https.";
});
} else { $("swState").textContent = "This browser has no service worker support."; }
})();