import { DOMAINS, PROPS, cssGradient, lutHex, normalize, propValue, partColor, fmtE, fmtRho, fmtNu, fmtProp, fmtLogTick, fmtInt } from './colors.js';
import { RangeFilter, AshbyChart, MiniHistogram } from './charts.js';
import { RenderOrbit, fetchJson } from './renders.js';
const HUB = 'https://huggingface.co';
const SPACE_PAGE = 'https://huggingface.co/spaces/rishitdagli/vomp-viewer';
const EMBEDDED = window.parent !== window;
const $ = (sel, root = document) => root.querySelector(sel);
const $$ = (sel, root = document) => [...root.querySelectorAll(sel)];
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
const sym = (s) => `${s} `;
const DEFAULTS = {
tab: 'gallery', q: '', ds: ['simready', 'residential', 'commercial'], fam: [], cat: [], split: [],
E: null, nu: null, rho: null, vox: null, multi: false, fric: false,
sort: 'featured', page: 1, per: 48, thumb: 'photo',
obj: null, view: '3d', color: 'E', range: 'global', variant: 0, rv: null,
};
const state = structuredClone(DEFAULTS);
const SORTS = [
['featured', 'Featured mix'],
['name', 'Name (A–Z)'],
['parts', 'Most parts'],
['mixed', 'Most material families'],
['voxels', 'Most voxels'],
['stiff', 'Stiffest part (max E)'],
['soft', 'Softest part (min E)'],
['dense', 'Densest part (max ρ)'],
['light', 'Lightest part (min ρ)'],
];
let INDEX;
let OBJS = [];
let FAMS = [];
let DSETS = [];
const BY_SHORT = new Map();
let filtered = [];
const ranges = {};
let viewer = null;
let viewerPromise = null;
let orbit = null;
let detailAbort = null;
let lastFocus = null;
let spaceBuilt = false;
const rationaleCache = new Map();
/* ---------------- data ---------------- */
function prepare(index) {
INDEX = index;
FAMS = index.families;
DSETS = index.datasets;
const { repo, rev } = index;
OBJS = index.objects.map((o) => {
const parts = o.p.map((p, i) => ({
i, usage: p[0], name: p[1], type: p[2], E: p[3], nu: p[4], rho: p[5], fam: p[6], frac: p[7], key: p[8], extras: p[9],
}));
const ds = DSETS[o.d][0];
const famShare = new Map();
const totalFrac = parts.reduce((s, p) => s + (p.frac || 0), 0);
parts.forEach((p) => {
const w = totalFrac > 0 ? p.frac || 0 : 1 / parts.length;
famShare.set(p.fam, (famShare.get(p.fam) || 0) + w);
});
const present = parts.filter((p) => p.frac == null || p.frac > 0);
const es = present.map((p) => p.E);
const rs = present.map((p) => p.rho);
const obj = {
...o, parts, ds, short: o.id.slice(0, 12), rendered: o.tv != null,
catKey: `${ds}:${o.c}`, splitName: INDEX.splits[o.s] || 'n/a',
famShare: [...famShare.entries()].sort((a, b) => b[1] - a[1]),
nFam: famShare.size,
maxE: Math.max(...es), minE: Math.min(...es), maxRho: Math.max(...rs), minRho: Math.min(...rs),
hasFric: parts.some((p) => p.extras),
url: (path) => `${HUB}/datasets/${repo}/resolve/${rev}/${path}`,
};
obj.hay = [o.n, o.c, o.sub, ds, DSETS[o.d][1], obj.splitName, ...parts.flatMap((p) => [p.usage, p.name, p.type, FAMS[p.fam][1]])]
.join(' ').toLowerCase().replace(/_/g, ' ');
obj.hayRaw = [o.n, ...parts.flatMap((p) => [p.usage, p.name])].join(' ').toLowerCase();
BY_SHORT.set(obj.short, obj);
return obj;
});
featuredOrder();
}
function hashStr(s) {
let h = 2166136261;
for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619);
return h >>> 0;
}
// Interleave datasets and categories so the default page is visually diverse.
function featuredOrder() {
const byDs = new Map();
for (const o of OBJS) {
if (!byDs.has(o.ds)) byDs.set(o.ds, new Map());
const cats = byDs.get(o.ds);
if (!cats.has(o.c)) cats.set(o.c, []);
cats.get(o.c).push(o);
}
const lanes = [];
for (const cats of byDs.values()) {
const groups = [...cats.values()].map((g) => g.sort((a, b) => b.nFam - a.nFam || Math.min(b.parts.length, 6) - Math.min(a.parts.length, 6) || hashStr(a.id) - hashStr(b.id)));
groups.sort((a, b) => b.length - a.length);
const lane = [];
for (let k = 0; groups.some((g) => k < g.length); k++) for (const g of groups) if (k < g.length) lane.push(g[k]);
lanes.push(lane);
}
let rank = 0;
for (let k = 0; lanes.some((l) => k < l.length); k++) for (const l of lanes) if (k < l.length) l[k].featured = rank++;
}
/* ---------------- URL state ---------------- */
const LIST_KEYS = ['ds', 'fam', 'cat', 'split'];
const RANGE_KEYS = ['E', 'nu', 'rho', 'vox'];
function readUrl() {
const p = new URLSearchParams(location.search);
for (const k of ['tab', 'q', 'sort', 'thumb', 'obj', 'view', 'color', 'range']) if (p.has(k)) state[k] = p.get(k);
for (const k of LIST_KEYS) if (p.has(k)) state[k] = p.get(k) === 'none' ? [] : p.get(k).split(k === 'cat' ? '|' : ',').filter(Boolean);
for (const k of RANGE_KEYS) if (p.has(k)) {
const v = p.get(k).split(',').map(Number);
if (v.length === 2 && v.every(Number.isFinite)) state[k] = v;
}
state.multi = p.get('multi') === '1';
state.fric = p.get('fric') === '1';
state.page = Math.max(1, parseInt(p.get('page') || '1', 10) || 1);
state.per = [24, 48, 96].includes(Number(p.get('per'))) ? Number(p.get('per')) : DEFAULTS.per;
state.variant = Math.max(0, Math.min(2, parseInt(p.get('var') || '0', 10) || 0));
state.rv = p.has('rv') ? parseInt(p.get('rv'), 10) : null;
if (!['gallery', 'space'].includes(state.tab)) state.tab = 'gallery';
if (!['3d', 'renders', 'mesh'].includes(state.view)) state.view = '3d';
if (!['E', 'nu', 'rho', 'part', 'fam'].includes(state.color)) state.color = 'E';
if (!SORTS.some(([k]) => k === state.sort)) state.sort = 'featured';
}
function queryString() {
const p = new URLSearchParams();
if (state.tab !== 'gallery') p.set('tab', state.tab);
if (state.q) p.set('q', state.q);
if (state.ds.slice().sort().join() !== DEFAULTS.ds.slice().sort().join()) p.set('ds', state.ds.join(',') || 'none');
for (const k of ['fam', 'cat', 'split']) if (state[k].length) p.set(k, state[k].join(k === 'cat' ? '|' : ','));
for (const k of RANGE_KEYS) if (state[k]) p.set(k, state[k].map((v) => +v.toFixed(3)).join(','));
if (state.multi) p.set('multi', '1');
if (state.fric) p.set('fric', '1');
if (state.sort !== DEFAULTS.sort) p.set('sort', state.sort);
if (state.page > 1) p.set('page', state.page);
if (state.per !== DEFAULTS.per) p.set('per', state.per);
if (state.thumb !== DEFAULTS.thumb) p.set('thumb', state.thumb);
if (state.obj) {
p.set('obj', state.obj);
if (state.view !== '3d') p.set('view', state.view);
if (state.color !== 'E') p.set('color', state.color);
if (state.range !== 'global') p.set('range', state.range);
if (state.variant) p.set('var', state.variant);
if (state.view === 'renders' && state.rv != null) p.set('rv', state.rv);
}
const s = p.toString();
return s ? `?${s}` : '';
}
let syncTimer = 0;
function syncUrl(now = false) {
clearTimeout(syncTimer);
const run = () => {
const qs = queryString();
history.replaceState(null, '', location.pathname + qs);
if (EMBEDDED) {
try { window.parent.postMessage({ queryString: qs, hash: '' }, 'https://huggingface.co'); } catch { /* not on the Hub */ }
}
};
if (now) run();
else syncTimer = setTimeout(run, 250);
}
function shareUrl() {
const qs = queryString();
return (EMBEDDED || location.hostname.endsWith('.hf.space') ? SPACE_PAGE : location.origin + location.pathname) + qs;
}
/* ---------------- filtering ---------------- */
function partFilterActive(skip) {
return (!skip.fam && state.fam.length) || state.E || state.nu || state.rho;
}
function partOk(p, skip) {
if (!skip.fam && state.fam.length && !state.fam.includes(FAMS[p.fam][0])) return false;
if (state.E && !inRange(Math.log10(p.E), state.E)) return false;
if (state.nu && !inRange(p.nu, state.nu)) return false;
if (state.rho && !inRange(Math.log10(p.rho), state.rho)) return false;
return true;
}
const inRange = (v, [lo, hi]) => v >= lo - 1e-9 && v <= hi + 1e-9;
function tokens() {
return state.q.toLowerCase().replace(/_/g, ' ').split(/\s+/).filter(Boolean);
}
function matches(o, skip = {}, toks = tokens()) {
if (!skip.ds && !state.ds.includes(o.ds)) return false;
if (!skip.cat && state.cat.length && !state.cat.includes(o.catKey)) return false;
if (!skip.split && state.split.length && !state.split.includes(o.splitName)) return false;
if (state.multi && o.nFam < 2) return false;
if (state.fric && !o.hasFric) return false;
if (state.vox && !(o.v && inRange(Math.log10(o.v), state.vox))) return false;
if (toks.length && !toks.every((t) => o.hay.includes(t) || o.hayRaw.includes(t))) return false;
if (partFilterActive(skip) && !o.parts.some((p) => partOk(p, skip))) return false;
return true;
}
function sortList(list) {
const by = {
featured: (a, b) => a.featured - b.featured,
name: (a, b) => a.n.localeCompare(b.n, 'en', { sensitivity: 'base', numeric: true }),
parts: (a, b) => b.parts.length - a.parts.length || a.featured - b.featured,
mixed: (a, b) => b.nFam - a.nFam || b.parts.length - a.parts.length,
voxels: (a, b) => (b.v || 0) - (a.v || 0),
stiff: (a, b) => b.maxE - a.maxE,
soft: (a, b) => a.minE - b.minE,
dense: (a, b) => b.maxRho - a.maxRho,
light: (a, b) => a.minRho - b.minRho,
}[state.sort];
return list.sort(by);
}
function refresh({ keepPage = false } = {}) {
if (!keepPage) state.page = 1;
const toks = tokens();
filtered = sortList(OBJS.filter((o) => matches(o, {}, toks)));
renderFacets(toks);
renderActiveChips();
renderGallery();
if (state.tab === 'space') renderSpace();
syncUrl();
}
/* ---------------- filters UI ---------------- */
function checkChip({ group, value, label, color, count, checked, note }) {
return `
${color ? ` ` : ''}
${esc(label)}${note ? ` ${esc(note)} ` : ''}
${fmtInt(count)}
`;
}
function buildFilters() {
const host = $('#filters-body');
host.innerHTML = `
`;
const allParts = OBJS.flatMap((o) => o.parts);
const specs = [
{ key: 'E', label: "Young's modulus E ", min: 1.5, max: 11.75, step: 0.05, fmt: (v) => fmtE(10 ** v, 2), values: allParts.map((p) => Math.log10(p.E)) },
{ key: 'nu', label: "Poisson's ratio ν ", min: 0, max: 0.5, step: 0.01, fmt: (v) => v.toFixed(2), values: allParts.map((p) => p.nu) },
{ key: 'rho', label: 'Density ρ ', min: 0, max: 4.35, step: 0.05, fmt: (v) => fmtRho(10 ** v), values: allParts.map((p) => Math.log10(p.rho)) },
];
for (const s of specs) {
const r = new RangeFilter({
id: `r-${s.key}`, label: s.label, min: s.min, max: s.max, step: s.step, format: s.fmt,
onChange: (v) => { state[s.key] = v; scheduleRefresh(); },
});
r.allValues = s.values;
if (state[s.key]) r.set(state[s.key][0], state[s.key][1], false);
ranges[s.key] = r;
$('#f-ranges').appendChild(r.el);
}
const vox = new RangeFilter({
id: 'r-vox', label: 'Voxel count (64³ grid)', min: 2, max: 5.45, step: 0.05,
format: (v) => fmtInt(Math.round(10 ** v)),
onChange: (v) => { state.vox = v; scheduleRefresh(); },
});
vox.allValues = OBJS.filter((o) => o.v).map((o) => Math.log10(o.v));
if (state.vox) vox.set(state.vox[0], state.vox[1], false);
ranges.vox = vox;
$('#f-vox').appendChild(vox.el);
host.addEventListener('change', (e) => {
const t = e.target;
if (t.dataset.group) {
const g = t.dataset.group;
const set = new Set(state[g]);
if (t.checked) set.add(t.value);
else set.delete(t.value);
state[g] = [...set];
refresh();
} else if (t.id === 'f-multi' || t.id === 'f-fric') {
state[t.id === 'f-multi' ? 'multi' : 'fric'] = t.checked;
refresh();
}
});
$('#f-cat-q').addEventListener('input', () => renderFacets(tokens()));
}
let refreshQueued = false;
function scheduleRefresh() {
if (refreshQueued) return;
refreshQueued = true;
requestAnimationFrame(() => { refreshQueued = false; refresh(); });
}
function facetCounts(skipKey, keyFn, toks) {
const counts = new Map();
for (const o of OBJS) {
if (!matches(o, { [skipKey]: true }, toks)) continue;
for (const k of keyFn(o)) counts.set(k, (counts.get(k) || 0) + 1);
}
return counts;
}
function renderFacets(toks) {
const focused = document.activeElement?.dataset?.group ? [document.activeElement.dataset.group, document.activeElement.value] : null;
renderFacetLists(toks);
if (focused) $$(`#filters-body input[data-group="${focused[0]}"]`).find((x) => x.value === focused[1])?.focus({ preventScroll: true });
}
function renderFacetLists(toks) {
const dsCounts = facetCounts('ds', (o) => [o.ds], toks);
$('#f-ds').innerHTML = DSETS.map(([k, label]) => checkChip({
group: 'ds', value: k, label, count: dsCounts.get(k) || 0, checked: state.ds.includes(k),
note: k === 'vegetation' ? 'annotations only' : '',
})).join('');
const famCounts = facetCounts('fam', (o) => {
const fams = new Set();
for (const p of o.parts) if (partOk(p, { fam: true })) fams.add(FAMS[p.fam][0]);
return fams;
}, toks);
$('#f-fam').innerHTML = FAMS.map(([k, label, color]) => checkChip({
group: 'fam', value: k, label, color, count: famCounts.get(k) || 0, checked: state.fam.includes(k),
})).join('');
const catCounts = facetCounts('cat', (o) => [o.catKey], toks);
const cq = ($('#f-cat-q')?.value || '').toLowerCase();
const groups = DSETS.map(([k, label]) => {
const cats = [...new Set(OBJS.filter((o) => o.ds === k).map((o) => o.c))]
.map((c) => ({ c, key: `${k}:${c}`, count: catCounts.get(`${k}:${c}`) || 0 }))
.filter((x) => !cq || x.c.toLowerCase().includes(cq))
.sort((a, b) => b.count - a.count || a.c.localeCompare(b.c));
if (!cats.length) return '';
return `
${esc(label)}
${cats.map((x) => checkChip({
group: 'cat', value: x.key, label: x.c, count: x.count, checked: state.cat.includes(x.key),
})).join('')}
`;
});
$('#f-cat').innerHTML = groups.join('') || 'No categories match.
';
const splitCounts = facetCounts('split', (o) => [o.splitName], toks);
$('#f-split').innerHTML = INDEX.splits.map((s) => checkChip({
group: 'split', value: s, label: s, count: splitCounts.get(s) || 0, checked: state.split.includes(s),
})).join('');
// Histograms: matching parts of matching objects for property sliders.
const matchedObjs = OBJS.filter((o) => matches(o, { fam: false }, toks));
for (const key of ['E', 'nu', 'rho']) {
const vals = [];
const saved = state[key];
state[key] = null;
for (const o of OBJS) {
if (!matches(o, {}, toks)) continue;
for (const p of o.parts) if (partOk(p, {})) vals.push(key === 'nu' ? p.nu : Math.log10(p[key]));
}
state[key] = saved;
ranges[key].setData(ranges[key].allValues, vals);
}
ranges.vox.setData(ranges.vox.allValues, matchedObjs.filter((o) => o.v).map((o) => Math.log10(o.v)));
$('#f-multi').checked = state.multi;
$('#f-fric').checked = state.fric;
const n = activeFilterCount();
$('#filters-count').textContent = n ? n : '';
$('#filters-count').hidden = !n;
}
function activeFilterCount() {
let n = state.fam.length + state.cat.length + state.split.length + (state.multi ? 1 : 0) + (state.fric ? 1 : 0);
n += RANGE_KEYS.filter((k) => state[k]).length;
if (state.ds.slice().sort().join() !== DEFAULTS.ds.slice().sort().join()) n += 1;
return n;
}
function renderActiveChips() {
const chips = [];
const add = (label, clear) => chips.push({ label, clear });
if (state.q) add(`“${state.q}”`, () => { state.q = ''; $('#search').value = ''; });
if (state.ds.slice().sort().join() !== DEFAULTS.ds.slice().sort().join()) add(`Datasets: ${state.ds.map((k) => DSETS.find((d) => d[0] === k)?.[1]).join(', ') || 'none'}`, () => { state.ds = [...DEFAULTS.ds]; });
for (const f of state.fam) add(FAMS.find((x) => x[0] === f)?.[1] || f, () => { state.fam = state.fam.filter((x) => x !== f); });
for (const c of state.cat) add(c.split(':').slice(1).join(':'), () => { state.cat = state.cat.filter((x) => x !== c); });
for (const s of state.split) add(`Split: ${s}`, () => { state.split = state.split.filter((x) => x !== s); });
const rl = { E: "Young's E", nu: "Poisson's ν", rho: 'Density', vox: 'Voxels' };
for (const k of RANGE_KEYS) if (state[k]) add(`${rl[k]} ${ranges[k].format(state[k][0])} – ${ranges[k].format(state[k][1])}`, () => { state[k] = null; ranges[k].set(ranges[k].min, ranges[k].max, false); });
if (state.multi) add('Multi-material', () => { state.multi = false; });
if (state.fric) add('Friction labels', () => { state.fric = false; });
const host = $('#active-filters');
host.innerHTML = chips.map((c, i) => `${esc(c.label)}× Remove filter `).join('')
+ (chips.length > 1 ? 'Clear all ' : '');
host.hidden = !chips.length;
host.onclick = (e) => {
const b = e.target.closest('.achip');
if (b) { chips[Number(b.dataset.i)].clear(); refresh(); return; }
if (e.target.closest('.achip-clear')) resetFilters();
};
}
function resetFilters() {
Object.assign(state, { q: '', ds: [...DEFAULTS.ds], fam: [], cat: [], split: [], E: null, nu: null, rho: null, vox: null, multi: false, fric: false });
$('#search').value = '';
for (const r of Object.values(ranges)) r.set(r.min, r.max, false);
refresh();
}
/* ---------------- gallery ---------------- */
function matBar(o, cls = 'matbar') {
return `${o.famShare.map(([f, w]) => ` `).join('')} `;
}
function thumbSrc(o, kind) {
return `thumbs/${o.id.slice(0, 16)}${kind === 'E' ? '_e' : ''}.webp`;
}
function cardHtml(o) {
const dom = o.parts[0];
const alt = state.thumb === 'E' ? 'photo' : 'E';
const media = o.rendered
? `
`
: `Annotations only `;
return `
${media}
${esc(DSETS[o.d][1])}
${o.parts.length} part${o.parts.length === 1 ? '' : 's'}
${esc(o.n)}
${esc(o.c)}${o.v ? ` · ${fmtInt(o.v)} voxels` : ''}
${matBar(o)}
${sym('E')} ${fmtE(dom.E, 2)} ${sym('ν')} ${fmtNu(dom.nu)} ${sym('ρ')} ${fmtRho(dom.rho, false)}
`;
}
function renderGallery() {
const total = filtered.length;
const pages = Math.max(1, Math.ceil(total / state.per));
state.page = Math.min(state.page, pages);
const start = (state.page - 1) * state.per;
const slice = filtered.slice(start, start + state.per);
const nParts = filtered.reduce((s, o) => s + o.parts.length, 0);
$('#result-count').innerHTML = total
? `${fmtInt(total)} object${total === 1 ? '' : 's'} · ${fmtInt(nParts)} parts${total > state.per ? ` · showing ${fmtInt(start + 1)}–${fmtInt(start + slice.length)}` : ''}`
: 'No objects match';
const grid = $('#grid');
grid.innerHTML = slice.length
? slice.map(cardHtml).join('')
: `No objects match these filters. Try widening a property range or removing a filter.
Reset filters `;
grid.classList.toggle('thumb-e', state.thumb === 'E');
$('#empty-reset')?.addEventListener('click', resetFilters);
renderPager(pages);
}
function renderPager(pages) {
const pager = $('#pager');
if (pages <= 1) { pager.innerHTML = ''; return; }
const cur = state.page;
const nums = new Set([1, pages, cur - 1, cur, cur + 1, cur - 2, cur + 2].filter((n) => n >= 1 && n <= pages));
const sorted = [...nums].sort((a, b) => a - b);
let html = `‹ Prev `;
let prev = 0;
for (const n of sorted) {
if (n - prev > 1) html += '… ';
html += `${n} `;
prev = n;
}
html += `Next › `;
pager.innerHTML = html;
}
function bindGallery() {
const grid = $('#grid');
grid.addEventListener('click', (e) => {
const card = e.target.closest('.card');
if (!card || e.metaKey || e.ctrlKey || e.shiftKey || e.button === 1) return;
e.preventDefault();
openDetail(card.dataset.obj, card);
});
let dwell = 0;
const warm = (e) => {
const card = e.target.closest('.card');
const alt = card?.querySelector('.card-img.alt[data-src]');
if (alt) { alt.src = alt.dataset.src; alt.removeAttribute('data-src'); }
clearTimeout(dwell);
if (card) dwell = setTimeout(() => prefetchObject(BY_SHORT.get(card.dataset.obj)), 150);
};
grid.addEventListener('pointerover', warm);
grid.addEventListener('focusin', warm);
$('#pager').addEventListener('click', (e) => {
const b = e.target.closest('.pg');
if (!b || b.disabled) return;
state.page = Number(b.dataset.p);
renderGallery();
syncUrl();
$('#results-top').scrollIntoView({ behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth', block: 'start' });
});
let qTimer = 0;
$('#search').addEventListener('input', (e) => {
clearTimeout(qTimer);
qTimer = setTimeout(() => { state.q = e.target.value.trim(); refresh(); }, 120);
});
$('#sort').innerHTML = SORTS.map(([k, l]) => `${l} `).join('');
$('#sort').addEventListener('change', (e) => { state.sort = e.target.value; refresh(); });
$('#per').addEventListener('change', (e) => { state.per = Number(e.target.value); refresh(); });
$$('.thumb-toggle button').forEach((b) => b.addEventListener('click', () => {
state.thumb = b.dataset.thumb;
$$('.thumb-toggle button').forEach((x) => x.setAttribute('aria-pressed', String(x === b)));
renderGallery();
syncUrl();
}));
$('#filters-open').addEventListener('click', () => toggleDrawer(true));
$('#filters-close').addEventListener('click', () => toggleDrawer(false));
$('#filters-apply').addEventListener('click', () => toggleDrawer(false));
$('#filters-reset').addEventListener('click', resetFilters);
$('.drawer-scrim').addEventListener('click', () => toggleDrawer(false));
}
function toggleDrawer(open) {
document.body.classList.toggle('drawer-open', open);
$('#filters-open').setAttribute('aria-expanded', String(open));
if (open) $('#filters-apply').textContent = `Show ${fmtInt(filtered.length)} objects`;
}
/* ---------------- tabs ---------------- */
function setTab(tab, { push = true } = {}) {
state.tab = tab;
for (const t of ['gallery', 'space']) {
$(`#tab-${t}`).hidden = t !== tab;
const btn = $(`.tab[data-tab="${t}"]`);
btn.setAttribute('aria-selected', String(t === tab));
btn.tabIndex = t === tab ? 0 : -1;
}
if (tab === 'space') renderSpace();
if (push) syncUrl();
}
/* ---------------- material space ---------------- */
let ashby;
let hists;
function buildSpace() {
spaceBuilt = true;
ashby = new AshbyChart($('#ashby'), {
families: FAMS,
fmtX: (v) => fmtLogTick('rho', v),
fmtY: (v) => fmtLogTick('E', v),
onHover: (p, x, y) => {
const tip = $('#ashby-tip');
if (!p) { tip.hidden = true; return; }
const ex = p.examples.slice(0, 3).map((o) => esc(o.n)).join(', ');
tip.innerHTML = ` ${esc(FAMS[p.fam][1])}
${sym('E')} ${fmtE(10 ** p.y)} · ${sym('ρ')} ${fmtRho(10 ** p.x)}
${fmtInt(p.count)} part${p.count === 1 ? '' : 's'}${p.matched !== p.count ? ` (${fmtInt(p.matched)} matching)` : ''} · e.g. ${ex}
Click to filter the gallery to this material
`;
tip.hidden = false;
const host = $('#ashby');
const left = Math.min(x + 14, host.clientWidth - tip.offsetWidth - 4);
tip.style.left = `${Math.max(4, left)}px`;
tip.style.top = `${Math.max(4, y - tip.offsetHeight - 10)}px`;
},
onClick: (p) => {
const e = Math.log10(10 ** p.y);
const r = p.x;
state.E = [Math.floor((e - 0.02) * 100) / 100, Math.ceil((e + 0.02) * 100) / 100];
state.rho = [Math.floor((r - 0.02) * 100) / 100, Math.ceil((r + 0.02) * 100) / 100];
state.fam = [FAMS[p.fam][0]];
ranges.E.set(state.E[0], state.E[1], false);
ranges.rho.set(state.rho[0], state.rho[1], false);
setTab('gallery');
refresh();
$('#results-top').scrollIntoView({ block: 'start' });
},
});
$('#ashby-legend').innerHTML = FAMS.map(([k, label, color], i) => ` ${esc(label)} `).join('');
$('#ashby-legend').addEventListener('click', (e) => {
const b = e.target.closest('.lg-chip');
if (!b) return;
const i = Number(b.dataset.i);
if (ashby.hiddenFams.has(i)) ashby.hiddenFams.delete(i);
else ashby.hiddenFams.add(i);
b.setAttribute('aria-pressed', String(!ashby.hiddenFams.has(i)));
ashby.draw();
});
hists = {
E: new MiniHistogram($('#h-E'), { title: "Young's modulus", min: 1.5, max: 11.75, fmt: (v) => fmtLogTick('E', v), ticks: [2, 4, 6, 8, 10] }),
nu: new MiniHistogram($('#h-nu'), { title: "Poisson's ratio", min: 0, max: 0.5, fmt: (v) => v.toFixed(1), ticks: [0, 0.1, 0.2, 0.3, 0.4, 0.5] }),
rho: new MiniHistogram($('#h-rho'), { title: 'Density (kg/m³)', min: 0, max: 4.35, fmt: (v) => fmtLogTick('rho', v), ticks: [0, 1, 2, 3, 4] }),
};
}
function median(arr) {
if (!arr.length) return null;
const s = [...arr].sort((a, b) => a - b);
const m = s.length >> 1;
return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
}
function renderSpace() {
if (!INDEX) return;
if (!spaceBuilt) buildSpace();
const matchedSet = new Set(filtered);
const agg = new Map();
const famStats = FAMS.map(() => ({ parts: 0, objs: new Set(), E: [], nu: [], rho: [] }));
const allE = [], allNu = [], allRho = [], mE = [], mNu = [], mRho = [];
for (const o of OBJS) {
if (!state.ds.includes(o.ds)) continue;
const objMatched = matchedSet.has(o);
for (const p of o.parts) {
const matched = objMatched && (!partFilterActive({}) || partOk(p, {}));
const key = `${p.E}|${p.rho}|${p.fam}`;
let a = agg.get(key);
if (!a) { a = { x: Math.log10(p.rho), y: Math.log10(p.E), fam: p.fam, count: 0, matched: 0, examples: [] }; agg.set(key, a); }
a.count++;
allE.push(Math.log10(p.E)); allNu.push(p.nu); allRho.push(Math.log10(p.rho));
if (matched) {
a.matched++;
if (a.examples.length < 3 && !a.examples.includes(o)) a.examples.push(o);
mE.push(Math.log10(p.E)); mNu.push(p.nu); mRho.push(Math.log10(p.rho));
const fs = famStats[p.fam];
fs.parts++; fs.objs.add(o); fs.E.push(p.E); fs.nu.push(p.nu); fs.rho.push(p.rho);
} else if (a.examples.length < 3 && !a.examples.includes(o) && !a.matched) {
a.examples.push(o);
}
}
}
ashby.setData([...agg.values()]);
hists.E.setData(allE, mE);
hists.nu.setData(allNu, mNu);
hists.rho.setData(allRho, mRho);
$('#fam-table tbody').innerHTML = FAMS.map(([k, label, color], i) => {
const s = famStats[i];
if (!s.parts) return '';
return ` ${esc(label)}${fmtInt(s.parts)} ${fmtInt(s.objs.size)} ${fmtE(median(s.E), 2)} ${fmtNu(median(s.nu))} ${fmtRho(median(s.rho), false)} `;
}).join('');
const catCounts = new Map();
for (const o of filtered) catCounts.set(o.catKey, (catCounts.get(o.catKey) || 0) + 1);
const top = [...catCounts.entries()].sort((a, b) => b[1] - a[1]).slice(0, 14);
const max = top[0]?.[1] || 1;
$('#cat-bars').innerHTML = top.map(([key, n]) => {
const [ds, ...rest] = key.split(':');
return `${esc(rest.join(':'))} ${esc(DSETS.find((d) => d[0] === ds)?.[1])} ${fmtInt(n)} `;
}).join('') || 'No objects match.
';
}
/* ---------------- detail view ---------------- */
function famChip(f) {
return ` ${esc(FAMS[f][1])} `;
}
function linkify(text) {
return esc(text)
.replace(/\(\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)\)/g, (_, label, url) => `(${label} )`)
.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g, (_, label, url) => `${label} `)
.replace(/\n/g, ' ');
}
async function gunzip(bytes) {
if (typeof DecompressionStream !== 'undefined') {
const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream('gzip'));
return new Uint8Array(await new Response(stream).arrayBuffer());
}
const { gunzipSync } = await import('https://cdn.jsdelivr.net/npm/fflate@0.8.2/esm/browser.js');
return gunzipSync(bytes);
}
// The static host serves files verbatim, so the larger JSON files ship gzipped. Suffixes avoid the
// Space's LFS rules (which add a slow CDN redirect): ".gzip" for small shards, and base64 text for the
// index, since binary files of that size are stored in LFS regardless of name.
async function fetchJsonGz(url) {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status} for ${url}`);
let bytes = new Uint8Array(await res.arrayBuffer());
if (bytes[0] === 0x1f && bytes[1] === 0x8b) bytes = await gunzip(bytes);
return JSON.parse(new TextDecoder().decode(bytes));
}
async function fetchIndex() {
const res = await fetch('data/index.json.gz.b64');
if (!res.ok) throw new Error(`HTTP ${res.status} for the index`);
const bin = atob((await res.text()).trim());
const bytes = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
return JSON.parse(new TextDecoder().decode(await gunzip(bytes)));
}
async function loadRationale(o) {
const prefix = o.id.slice(0, 2);
if (!rationaleCache.has(prefix)) {
rationaleCache.set(prefix, fetchJsonGz(`data/rationale/${prefix}.json.gzip`).catch(() => ({})));
}
const shard = await rationaleCache.get(prefix);
return shard[o.id] || [];
}
function partSwatch(o, p) {
const mode = state.color;
if (mode === 'part') return partColor(p.i);
if (mode === 'fam') return FAMS[p.fam][2];
const dom = viewer?.domain ? viewer.domain(o.parts) : undefined;
return lutHex(mode, normalize(mode, p[mode], dom || DOMAINS[mode]));
}
// USD material prim names such as "opaque__metal__aluminium_pallet" are internal keys, not labels.
function readable(s) {
return !!s && !s.includes('__') && !/^[0-9a-f]{12,}$/i.test(s);
}
function renderParts(o) {
const list = $('#d-parts');
list.innerHTML = o.parts.map((p) => {
const share = p.frac == null ? '' : ` ${p.frac > 0 ? (p.frac * 100 < 1 ? '<1' : (p.frac * 100).toFixed(0)) + '%' : 'no voxels'} `;
const ex = p.extras ? `` : '';
const matLine = [p.name, p.type].filter((x, i, a) => readable(x) && a.indexOf(x) === i && x !== p.usage).map(esc).join(' · ');
return `
${esc(p.usage)} ${famChip(p.fam)}
${matLine ? `
${matLine}
` : ''}
${sym('E')} ${fmtE(p.E)} ${sym('ν')} ${fmtNu(p.nu)} ${sym('ρ')} ${fmtRho(p.rho)} ${share}
${ex}
VLM rationale Loading…
`;
}).join('');
loadRationale(o).then((texts) => {
if (state.obj !== o.short) return;
$$('.part', list).forEach((li, k) => {
const body = $('.why-body', li);
body.innerHTML = texts[k] ? linkify(texts[k]) : 'Not available. ';
});
});
}
function updateSwatches(o) {
$$('#d-parts .part').forEach((li) => {
const p = o.parts[Number(li.dataset.part)];
$('.swatch', li).style.background = partSwatch(o, p);
});
}
function detailList() {
return filtered.length ? filtered : OBJS;
}
function openDetail(short, fromEl, { restore = false } = {}) {
const o = BY_SHORT.get(short);
if (!o) return;
if (!state.obj) lastFocus = fromEl || document.activeElement;
const changed = state.obj !== short;
state.obj = short;
if (changed) {
if (!restore) {
state.variant = 0;
state.rv = null;
}
$$('#ctl-variant button').forEach((b) => b.setAttribute('aria-pressed', String(Number(b.dataset.var) === state.variant)));
resetHighlight();
}
const d = $('#detail');
d.hidden = false;
document.body.classList.add('detail-open');
renderDetail(o, changed);
syncUrl();
requestAnimationFrame(() => d.classList.add('is-open'));
if (!d.contains(document.activeElement)) $('#d-close').focus({ preventScroll: true });
}
function closeDetail() {
if (!state.obj) return;
state.obj = null;
detailAbort?.abort();
orbit?.stopSpin();
viewer?.setActive(false);
const d = $('#detail');
d.classList.remove('is-open');
d.hidden = true;
document.body.classList.remove('detail-open');
syncUrl(true);
if (lastFocus && document.contains(lastFocus)) lastFocus.focus({ preventScroll: true });
}
function step(delta) {
const list = detailList();
const cur = list.findIndex((o) => o.short === state.obj);
const next = list[(cur + delta + list.length) % list.length];
if (next) openDetail(next.short);
}
function renderDetail(o, changed) {
const list = detailList();
const pos = list.findIndex((x) => x === o);
$('#d-title').textContent = o.n;
$('#d-chips').innerHTML = `${esc(DSETS[o.d][1])} ${esc(o.c)} `;
$('#d-pos').textContent = pos >= 0 ? `${fmtInt(pos + 1)} / ${fmtInt(list.length)}` : '';
$('#d-hub').href = o.rendered ? `${HUB}/datasets/${INDEX.repo}/tree/${INDEX.rev}/renders/${o.id}` : `${HUB}/datasets/${INDEX.repo}`;
const famList = o.famShare.map(([f, w]) => `${famChip(f)} ${(w * 100).toFixed(0)}% `).join('');
$('#d-summary').innerHTML = `
Parts ${o.parts.length}
Voxels ${o.v ? fmtInt(o.v) : '–'}
Interior voxels ${o.iv != null ? fmtInt(o.iv) : '–'}
Stiffest part ${fmtE(o.maxE, 2)}
${matBar(o, 'matbar matbar-lg')}
${famList}
`;
renderParts(o);
$$('.stage-tab').forEach((b) => {
b.disabled = !o.rendered;
});
if (!o.rendered) {
showStageMessage('No renders or voxels for this object. This vegetation asset has part-level material annotations only.
');
return;
}
if (changed) {
detailAbort?.abort();
detailAbort = new AbortController();
}
setView(state.view, o, changed);
if (pos >= 0) setTimeout(() => [1, -1].forEach((d) => prefetchObject(list[(pos + d + list.length) % list.length])), 300);
}
function showStageMessage(html) {
$('#stage').dataset.mode = 'message';
$('#stage-msg').innerHTML = html;
$('#stage-controls').hidden = true;
$('#legend').hidden = true;
$$('.stage-tab').forEach((b) => b.setAttribute('aria-selected', 'false'));
hidePlaceholder();
viewer?.setActive(false);
}
function setView(view, o = BY_SHORT.get(state.obj), force = false) {
if (!o) return;
state.view = view;
$$('.stage-tab').forEach((b) => b.setAttribute('aria-selected', String(b.dataset.view === view)));
$('#stage-controls').hidden = false;
const stage = $('#stage');
stage.dataset.mode = view;
$('#stage-msg').innerHTML = '';
$('#ctl-3d').hidden = view === 'renders';
$('#ctl-renders').hidden = view !== 'renders';
$('#ctl-slice').hidden = view !== '3d';
$('#ctl-variant').hidden = view !== '3d' || !o.a?.length;
orbit?.stopSpin();
$('#ctl-spin').setAttribute('aria-pressed', 'false');
$('#ctl-isolate').hidden = highlight.pinned < 0 || view !== '3d';
hidePlaceholder();
if (view === 'renders') {
viewer?.setActive(false);
$('#legend').hidden = true;
showRenders(o);
} else {
showViewer(o, view, force);
}
syncUrl();
}
let viewerModule = null;
function ensureViewerModule() {
if (!viewerModule) viewerModule = import('./viewer3d.js').catch((err) => { viewerModule = null; throw err; });
return viewerModule;
}
// Small LRU of voxel NPZ downloads so hover/neighbour prefetches make opening instant.
const voxelBuffers = new Map();
function voxelBuffer(url) {
let p = voxelBuffers.get(url);
if (p) {
voxelBuffers.delete(url);
} else {
p = fetch(url).then((r) => {
if (!r.ok) throw new Error(`HTTP ${r.status} for voxel field`);
return r.arrayBuffer();
});
p.catch(() => voxelBuffers.delete(url));
}
voxelBuffers.set(url, p);
while (voxelBuffers.size > 16) voxelBuffers.delete(voxelBuffers.keys().next().value);
return p;
}
function voxelUrl(o, variant = 0) {
const sha = variant && o.a?.[variant - 1] ? o.a[variant - 1][0] : o.id;
return o.url(`voxels/${sha}_with_materials.npz`);
}
function prefetchObject(o) {
if (o?.rendered && !navigator.connection?.saveData) voxelBuffer(voxelUrl(o)).catch(() => {});
}
async function ensureViewer() {
if (viewer) return viewer;
if (!viewerPromise) {
viewerPromise = ensureViewerModule().then((m) => {
viewer = new m.PropertyViewer($('#viewer-host'), {
onHover: showTooltip,
onContextLost: () => showStageMessage('The 3D view lost its WebGL context. Reload the page to restore it; the Renders tab still works.
'),
});
viewer.families = FAMS;
viewer.setColor({ mode: state.color, range: state.range });
return viewer;
}).catch((err) => {
viewerPromise = null;
throw err;
});
}
return viewerPromise;
}
const loaded = { voxKey: null, meshKey: null };
function showPlaceholder(o, kind) {
const ph = $('#stage-ph');
ph.src = thumbSrc(o, kind);
ph.hidden = false;
}
function hidePlaceholder() {
$('#stage-ph').hidden = true;
}
async function showViewer(o, view, force) {
const stage = $('#stage');
stage.classList.add('is-loading');
$('#stage-status').textContent = view === 'mesh' ? '' : 'Loading voxel field…';
const url = view === '3d' ? voxelUrl(o, state.variant) : null;
const key = url && `${o.id}:${url}`;
if (url && (loaded.voxKey !== key || force)) {
// Start the download now so it overlaps with loading three.js, and show the preview meanwhile.
voxelBuffer(url).catch(() => {});
if (!state.variant) showPlaceholder(o, state.color === 'E' && state.range === 'global' ? 'E' : 'photo');
}
let v;
try {
v = await ensureViewer();
} catch (err) {
stage.classList.remove('is-loading');
showStageMessage(`3D preview unavailable. ${esc(err.message || 'WebGL could not be initialised')}. The Renders tab still works.
`);
$('#stage-controls').hidden = false;
return;
}
if (state.obj !== o.short || state.view !== view) return;
v.setUpAxis(o.up || 'Z');
const signal = detailAbort?.signal;
try {
if (view === '3d') {
if (loaded.voxKey !== key || force) {
v.clearContent();
v.setActive(true);
loaded.voxKey = null;
const buffer = await voxelBuffer(url);
if (state.obj !== o.short || state.view !== view) return;
await v.loadVoxels(null, o.parts, { buffer });
loaded.voxKey = key;
if (state.obj !== o.short || state.view !== view) return;
resetSlice(o);
v.showVoxels();
v.frameView(o.cam);
} else {
v.showVoxels();
v.frameView();
}
hidePlaceholder();
const meta = v.vox.meta || {};
$('#stage-status').textContent = `${fmtInt(v.vox.n)} voxels · ${meta.grid_resolution || 64}³ grid · ${fmtInt(meta.interior_voxel_count ?? o.iv)} interior`;
} else {
if (loaded.meshKey !== o.id) {
stage.classList.remove('is-loading');
$('#stage').dataset.mode = 'mesh-idle';
const mb = o.ms ? o.ms / 1e6 : null;
$('#mesh-size').textContent = mb ? `${mb.toFixed(1)} MB` : 'size unknown';
$('#mesh-warn').hidden = !(mb > 40);
$('#mesh-warn').textContent = mb > 40 ? `This is one of the larger meshes in the dataset; it may take a while to download and can be slow on phones.` : '';
$('#legend').hidden = true;
$('#stage-status').textContent = '';
v.setActive(false);
fetchJson(o.url(`renders/${o.id}/transforms.json`), signal).then((tr) => {
const tri = tr.mesh?.triangle_count;
if (tri && state.obj === o.short && state.view === 'mesh') $('#mesh-size').textContent = `${mb ? `${mb.toFixed(1)} MB · ` : ''}${fmtInt(tri)} triangles`;
}).catch(() => {});
return;
}
v.showMesh();
v.frameView(o.cam);
const tris = v.meshData.index.length / 3;
if (tris > 1.5e6) {
$('#ctl-rotate').setAttribute('aria-pressed', 'false');
}
$('#stage-status').textContent = `${fmtInt(tris)} triangles · coloured by part annotation${tris > 1.5e6 ? ' · auto-rotate paused for this large mesh' : ''}`;
}
} catch (err) {
if (err.name === 'AbortError') return;
stage.classList.remove('is-loading');
showStageMessage(`Could not load the ${view === 'mesh' ? 'mesh' : 'voxel field'}. ${esc(err.message)}
`);
$('#stage-controls').hidden = false;
return;
}
stage.classList.remove('is-loading');
v.setActive(true);
v.setAutoRotate($('#ctl-rotate').getAttribute('aria-pressed') === 'true');
updateLegend(o);
updateSwatches(o);
}
async function loadMeshNow() {
const o = BY_SHORT.get(state.obj);
if (!o) return;
const stage = $('#stage');
stage.dataset.mode = 'mesh';
stage.classList.add('is-loading');
const bar = $('#mesh-progress');
bar.hidden = false;
try {
const v = await ensureViewer();
const tr = await fetchJson(o.url(`renders/${o.id}/transforms.json`), detailAbort?.signal);
await v.loadMesh(o.url(`renders/${o.id}/mesh.ply`), o.parts, tr.mesh?.segment_keys, {
signal: detailAbort?.signal,
expected: o.ms,
onProgress: (got, total) => {
const pct = total ? Math.min(100, (got / total) * 100) : 0;
$('#stage-status').textContent = `Downloading mesh… ${(got / 1e6).toFixed(1)}${total ? ` / ${(total / 1e6).toFixed(1)}` : ''} MB`;
bar.style.setProperty('--p', `${pct}%`);
},
});
loaded.meshKey = o.id;
bar.hidden = true;
if (state.obj === o.short && state.view === 'mesh') showViewer(o, 'mesh');
} catch (err) {
bar.hidden = true;
stage.classList.remove('is-loading');
if (err.name !== 'AbortError') showStageMessage(`Could not load the mesh. ${esc(err.message)}
`);
}
}
async function showRenders(o) {
const stage = $('#stage');
stage.classList.add('is-loading');
$('#stage-status').textContent = 'Loading camera poses…';
if (!orbit) {
orbit = new RenderOrbit($('#orbit-host'), {
onView: (i) => {
state.rv = i;
syncUrl();
},
});
}
if (state.rv == null || state.rv === o.tv) orbit.placeholder(thumbSrc(o, 'photo'));
try {
const tr = await fetchJson(o.url(`renders/${o.id}/transforms.json`), detailAbort?.signal);
if (state.obj !== o.short || state.view !== 'renders') return;
const start = state.rv != null && state.rv >= 0 && state.rv < tr.frames.length ? state.rv : o.tv;
orbit.setFrames(tr.frames, o.up || tr.stage_up_axis || 'Z', (file) => o.url(`renders/${o.id}/${file}`), start);
$('#stage-status').textContent = `${tr.frames.length} views`;
} catch (err) {
if (err.name === 'AbortError') return;
showStageMessage(`Could not load the renders. ${esc(err.message)}
`);
$('#stage-controls').hidden = false;
} finally {
stage.classList.remove('is-loading');
}
}
function updateLegend(o) {
const lg = $('#legend');
const mode = state.color;
lg.hidden = false;
if (mode === 'part' || mode === 'fam') {
const items = mode === 'part'
? o.parts.filter((p) => p.frac == null || p.frac > 0).slice(0, 8).map((p) => [partColor(p.i), p.usage])
: o.famShare.map(([f]) => [FAMS[f][2], FAMS[f][1]]);
const more = mode === 'part' && o.parts.length > 8 ? `+${o.parts.length - 8} more in the list
` : '';
lg.innerHTML = `${mode === 'part' ? 'Parts' : 'Material family'}
${items.map(([c, l]) => ` ${esc(l)}
`).join('')}${more}`;
return;
}
const dom = viewer.domain(o.parts) || DOMAINS[mode];
const P = PROPS[mode];
const unit = mode === 'rho' ? ', kg/m³' : '';
const ticks = legendTicks(mode, dom);
lg.innerHTML = `${P.label} (${P.log ? 'log' : 'linear'}${unit})
${ticks.map((t, i) => `${t.label} `).join('')}
${state.range === 'global' ? 'Shared scale across the dataset' : 'Scaled to this object'}
`;
}
// Round ticks inside the colour domain: decades for log properties, nice steps for ν.
function legendTicks(mode, [lo, hi]) {
const P = PROPS[mode];
let vals = [];
if (P.log) {
const first = Math.ceil(lo - 1e-9);
const last = Math.floor(hi + 1e-9);
const n = last - first + 1;
const maxTicks = mode === 'rho' ? 5 : 3;
const stepDec = Math.max(1, Math.ceil(n / maxTicks));
for (let v = first; v <= last; v += stepDec) vals.push(v);
} else {
const span = hi - lo;
const stepNu = span > 0.3 ? 0.1 : span > 0.12 ? 0.05 : span > 0.05 ? 0.02 : 0.01;
for (let v = Math.ceil((lo - 1e-9) / stepNu) * stepNu; v <= hi + 1e-9; v += stepNu) vals.push(+v.toFixed(3));
}
if (vals.length < 2) vals = [lo, ...vals.filter((v) => v - lo > 0.15 * (hi - lo) && hi - v > 0.15 * (hi - lo)), hi];
const label = (v) => (mode === 'E' ? fmtE(10 ** v, 2) : mode === 'rho' ? fmtLogTick('rho', v) : fmtNu(v));
return vals.map((v) => ({ pos: (v - lo) / (hi - lo || 1), label: label(v) }));
}
const highlight = { hover: -1, pinned: -1, isolate: false };
function applyHighlight() {
$$('#d-parts .part').forEach((li) => li.classList.toggle('is-pinned', Number(li.dataset.part) === highlight.pinned));
const iso = $('#ctl-isolate');
iso.hidden = highlight.pinned < 0 || state.view !== '3d';
if (!viewer || state.view === 'renders') return;
const isolate = highlight.isolate && highlight.pinned >= 0;
viewer.setColor({ highlight: isolate ? highlight.pinned : highlight.hover >= 0 ? highlight.hover : highlight.pinned, isolate });
}
function resetHighlight() {
Object.assign(highlight, { hover: -1, pinned: -1, isolate: false });
$('#ctl-isolate').setAttribute('aria-pressed', 'false');
$('#ctl-isolate').hidden = true;
viewer?.setColor({ highlight: -1, isolate: false });
}
// Cut along the axis that points most towards the initial camera, removing the near half first.
function resetSlice(o) {
const cam = o.cam || [1, 0, 0];
const axis = [0, 1, 2].reduce((best, a) => (Math.abs(cam[a]) > Math.abs(cam[best]) ? a : best), 0);
const flip = cam[axis] < 0;
$('#slice').value = 100;
$('#slice-val').textContent = 'off';
$('#slice-axis').value = String(axis);
$('#slice-flip').setAttribute('aria-pressed', String(flip));
viewer?.setSlice({ axis, flip, t: 0.5 });
}
function showTooltip(hit) {
const tip = $('#vox-tip');
const o = BY_SHORT.get(state.obj);
$$('#d-parts .part.is-hover').forEach((x) => x.classList.remove('is-hover'));
if (!hit || !o) { tip.hidden = true; return; }
const p = o.parts[hit.part];
tip.innerHTML = `${p ? esc(p.usage) : 'Unmatched segment'}
${p ? `${famChip(p.fam)}
` : ''}
${sym('E')} ${fmtE(hit.E)} · ${sym('ν')} ${fmtNu(hit.nu)} · ${sym('ρ')} ${fmtRho(hit.rho)}
${hit.surface != null ? `${hit.surface ? 'Surface voxel' : 'Interior voxel'}
` : ''}`;
tip.hidden = false;
const host = $('#stage');
const x = Math.min(hit.x + 14, host.clientWidth - tip.offsetWidth - 6);
const y = hit.y + 16 + tip.offsetHeight > host.clientHeight ? hit.y - tip.offsetHeight - 10 : hit.y + 16;
tip.style.left = `${Math.max(6, x)}px`;
tip.style.top = `${Math.max(6, y)}px`;
if (p) {
const li = $(`#d-parts .part[data-part="${p.i}"]`);
li?.classList.add('is-hover');
if (hit.click) li?.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
}
}
function bindDetail() {
$('#d-close').addEventListener('click', closeDetail);
$('.detail-backdrop').addEventListener('click', closeDetail);
$('#d-prev').addEventListener('click', () => step(-1));
$('#d-next').addEventListener('click', () => step(1));
$('#d-copy').addEventListener('click', async () => {
const url = shareUrl();
try {
await navigator.clipboard.writeText(url);
flash($('#d-copy'), 'Link copied');
} catch {
prompt('Copy this link:', url);
}
});
$$('.stage-tab').forEach((b) => b.addEventListener('click', () => setView(b.dataset.view)));
$('#mesh-load').addEventListener('click', loadMeshNow);
$$('#ctl-color button').forEach((b) => b.addEventListener('click', () => {
state.color = b.dataset.color;
$$('#ctl-color button').forEach((x) => x.setAttribute('aria-pressed', String(x === b)));
$('#ctl-range').hidden = state.color === 'part' || state.color === 'fam';
viewer?.setColor({ mode: state.color });
const o = BY_SHORT.get(state.obj);
if (o && viewer) { updateLegend(o); updateSwatches(o); }
syncUrl();
}));
$$('#ctl-range button').forEach((b) => b.addEventListener('click', () => {
state.range = b.dataset.range;
$$('#ctl-range button').forEach((x) => x.setAttribute('aria-pressed', String(x === b)));
viewer?.setColor({ range: state.range });
const o = BY_SHORT.get(state.obj);
if (o && viewer) { updateLegend(o); updateSwatches(o); }
syncUrl();
}));
$('#slice').addEventListener('input', (e) => {
const t = (Number(e.target.value) / 100) - 0.5;
viewer?.setSlice({ t });
$('#slice-val').textContent = Number(e.target.value) >= 100 ? 'off' : `${e.target.value}%`;
});
$('#slice-axis').addEventListener('change', (e) => viewer?.setSlice({ axis: Number(e.target.value) }));
$('#slice-flip').addEventListener('click', (e) => {
const on = e.currentTarget.getAttribute('aria-pressed') !== 'true';
e.currentTarget.setAttribute('aria-pressed', String(on));
viewer?.setSlice({ flip: on });
});
$$('#ctl-variant button').forEach((b) => b.addEventListener('click', () => {
state.variant = Number(b.dataset.var);
$$('#ctl-variant button').forEach((x) => x.setAttribute('aria-pressed', String(x === b)));
const o = BY_SHORT.get(state.obj);
if (o) showViewer(o, '3d');
syncUrl();
}));
$('#ctl-rotate').addEventListener('click', (e) => {
const on = e.currentTarget.getAttribute('aria-pressed') !== 'true';
e.currentTarget.setAttribute('aria-pressed', String(on));
viewer?.setAutoRotate(on);
});
$('#ctl-reset').addEventListener('click', () => {
const o = BY_SHORT.get(state.obj);
if (viewer && o) viewer.frameView(o.cam);
});
$('#ctl-png').addEventListener('click', () => {
if (!viewer) return;
const a = document.createElement('a');
a.href = viewer.snapshot();
a.download = `vomp_${BY_SHORT.get(state.obj)?.n || 'object'}_${state.color}.png`;
a.click();
});
$('#ctl-spin').addEventListener('click', (e) => {
const on = e.currentTarget.getAttribute('aria-pressed') !== 'true';
e.currentTarget.setAttribute('aria-pressed', String(on));
orbit?.spin(on);
});
const parts = $('#d-parts');
parts.addEventListener('pointerover', (e) => {
const li = e.target.closest('.part');
const i = li ? Number(li.dataset.part) : -1;
if (i === highlight.hover) return;
highlight.hover = i;
applyHighlight();
});
parts.addEventListener('pointerleave', () => {
highlight.hover = -1;
applyHighlight();
});
parts.addEventListener('click', (e) => {
if (e.target.closest('details, a')) return;
const li = e.target.closest('.part');
if (!li || state.view === 'renders') return;
const i = Number(li.dataset.part);
highlight.pinned = highlight.pinned === i ? -1 : i;
if (highlight.pinned < 0) {
highlight.isolate = false;
$('#ctl-isolate').setAttribute('aria-pressed', 'false');
}
applyHighlight();
});
$('#ctl-isolate').addEventListener('click', (e) => {
highlight.isolate = e.currentTarget.getAttribute('aria-pressed') !== 'true';
e.currentTarget.setAttribute('aria-pressed', String(highlight.isolate));
applyHighlight();
});
document.addEventListener('keydown', (e) => {
if (!state.obj) {
if (e.key === '/' && document.activeElement?.tagName !== 'INPUT') { e.preventDefault(); $('#search').focus(); }
return;
}
if (e.key === 'Escape') { e.preventDefault(); closeDetail(); return; }
const tag = document.activeElement?.tagName;
if (['INPUT', 'SELECT', 'TEXTAREA'].includes(tag) || document.activeElement?.closest('.orbit-stage')) return;
if (e.key === 'ArrowRight') { e.preventDefault(); step(1); }
if (e.key === 'ArrowLeft') { e.preventDefault(); step(-1); }
});
$('#detail').addEventListener('keydown', (e) => {
if (e.key !== 'Tab') return;
const focusables = $$('#detail button:not([disabled]), #detail a[href], #detail input, #detail select, #detail summary, #detail [tabindex="0"]').filter((x) => x.offsetParent !== null);
if (!focusables.length) return;
const first = focusables[0];
const last = focusables[focusables.length - 1];
if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
});
}
function flash(btn, text) {
const old = btn.dataset.label || btn.textContent;
btn.dataset.label = old;
btn.classList.add('is-flash');
btn.querySelector('.btn-text') ? (btn.querySelector('.btn-text').textContent = text) : (btn.textContent = text);
setTimeout(() => {
btn.classList.remove('is-flash');
btn.querySelector('.btn-text') ? (btn.querySelector('.btn-text').textContent = old) : (btn.textContent = old);
}, 1600);
}
/* ---------------- boot ---------------- */
// Object total set by the user (1,740 incl. vegetation); voxels and parts from Table 10 of
// arXiv:2510.22975v2. The paper gives no total category count, so there is no categories chip.
const PAPER_STATS = [
['1,740', 'objects'],
['37.3M', `voxels with ${sym('E')}, ${sym('ν')}, ${sym('ρ')}`],
['8,089', 'annotated parts'],
];
function renderStats() {
$('#stats').innerHTML = PAPER_STATS.map(([n, l]) => `${n} ${l}
`).join('');
}
function applyStateToControls() {
$('#search').value = state.q;
$('#sort').value = state.sort;
$('#per').value = String(state.per);
$$('.thumb-toggle button').forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.thumb === state.thumb)));
$$('#ctl-color button').forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.color === state.color)));
$$('#ctl-range button').forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.range === state.range)));
$('#ctl-range').hidden = state.color === 'part' || state.color === 'fam';
$$('#ctl-variant button').forEach((b) => b.setAttribute('aria-pressed', String(Number(b.dataset.var) === state.variant)));
const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
$('#ctl-rotate').setAttribute('aria-pressed', String(!reduce));
}
async function init() {
readUrl();
renderStats();
$$('.tab').forEach((b) => b.addEventListener('click', () => setTab(b.dataset.tab)));
$('.tabs').addEventListener('keydown', (e) => {
const tabs = $$('.tab');
const i = tabs.indexOf(document.activeElement);
if (i < 0 || !['ArrowLeft', 'ArrowRight'].includes(e.key)) return;
const next = tabs[(i + (e.key === 'ArrowRight' ? 1 : tabs.length - 1)) % tabs.length];
next.focus();
setTab(next.dataset.tab);
});
let index;
try {
index = await fetchIndex().catch(() => fetchJsonGz('data/index.json'));
} catch (err) {
$('#grid').innerHTML = `Could not load the dataset index. ${esc(err.message)}
`;
return;
}
prepare(index);
buildFilters();
bindGallery();
bindDetail();
applyStateToControls();
const page = state.page;
refresh();
state.page = page;
renderGallery();
setTab(state.tab, { push: false });
if (state.obj) {
const o = BY_SHORT.get(state.obj) || OBJS.find((x) => x.id.startsWith(state.obj));
state.obj = null;
if (o) openDetail(o.short, null, { restore: true });
}
syncUrl(true);
document.body.classList.add('is-ready');
// Fetch three.js and the viewer while the user is still browsing the gallery.
if (!navigator.connection?.saveData) whenIdle(() => ensureViewerModule().catch(() => {}));
}
function whenIdle(fn) {
if ('requestIdleCallback' in window) requestIdleCallback(fn, { timeout: 4000 });
else setTimeout(fn, 1500);
}
init();