Spaces:
Running
Running
Download app.js from projectsim/simready-library: direct link, hf CLI and curl.
- Browser
- Download file 35.9 kB
-
https://huggingface.co/spaces/projectsim/simready-library/resolve/main/app.js
- Command line
-
hf download hf://spaces/projectsim/simready-library/app.js
-
curl -L -o app.js https://huggingface.co/spaces/projectsim/simready-library/resolve/main/app.js
35.9 kB
| ; | |
| // projectsim SimReady Library: a static catalog of data/catalog.json (built by | |
| // tools/build_catalog.py). Thumbnails and files load straight from the public dataset, | |
| // pinned to the commit the catalog was built from; 3D previews come from previews/ | |
| // in this Space (built by tools/make_previews.py) and are shown by viewer.js. | |
| const HF = "https://huggingface.co"; | |
| const SPACE_URL = "https://huggingface.co/spaces/projectsim/simready-library"; | |
| // A private Space authorises each file request by the __sign token in the page URL, but | |
| // files loaded later by a script (import(), the 3D model) send the script's address as the | |
| // referrer, so they carry the token themselves. | |
| const SIGN = new URLSearchParams(location.search).get("__sign"); | |
| const signed = (path) => SIGN ? `${path}${path.includes("?") ? "&" : "?"}__sign=${encodeURIComponent(SIGN)}` : path; | |
| const API_DOCS = "https://docs.projectsim.ai/getting-started/quickstart?utm_source=hf_space&utm_medium=detail&utm_content=simready-library"; | |
| const FACETS = [ | |
| { key: "moving", title: "Moving parts", options: [ | |
| ["yes", "Has moving parts", (a) => a.joints.length > 0], | |
| ["no", "Rigid", (a) => a.joints.length === 0 && a.kind !== "scene"], | |
| ] }, | |
| { key: "joint", title: "Joint type", options: [ | |
| ["hinge", "Hinge", (a) => a.joints.some((j) => j.type === "hinge")], | |
| ["slider", "Slider", (a) => a.joints.some((j) => j.type === "slider")], | |
| ] }, | |
| { key: "size", title: "Size (longest side)", options: [ | |
| ["s", "< 15 cm", (a) => maxDim(a) < 0.15], | |
| ["m", "15–50 cm", (a) => maxDim(a) >= 0.15 && maxDim(a) < 0.5], | |
| ["l", "50 cm–1.5 m", (a) => maxDim(a) >= 0.5 && maxDim(a) < 1.5], | |
| ["xl", "1.5 m +", (a) => maxDim(a) >= 1.5], | |
| ] }, | |
| { key: "mass", title: "Mass", options: [ | |
| ["xs", "< 100 g", (a) => a.mass != null && a.mass < 0.1], | |
| ["s", "100 g–1 kg", (a) => a.mass >= 0.1 && a.mass < 1], | |
| ["m", "1–10 kg", (a) => a.mass >= 1 && a.mass < 10], | |
| ["l", "10 kg +", (a) => a.mass >= 10], | |
| ] }, | |
| { key: "mount", title: "Placement", options: [ | |
| ["free", "Free-standing", (a) => !a.mounted && a.kind !== "scene"], | |
| ["fixed", "Mounted (fixed base)", (a) => a.mounted], | |
| ] }, | |
| ]; | |
| const $ = (id) => document.getElementById(id); | |
| const el = (tag, attrs = {}, ...kids) => { | |
| const svgTags = { svg: 1, path: 1, circle: 1 }; | |
| const n = svgTags[tag] ? document.createElementNS("http://www.w3.org/2000/svg", tag) : document.createElement(tag); | |
| for (const [k, v] of Object.entries(attrs)) { | |
| if (v == null || v === false) continue; | |
| if (k === "class") n.setAttribute("class", v); | |
| else if (k.startsWith("on")) n.addEventListener(k.slice(2), v); | |
| else n.setAttribute(k, v === true ? "" : v); | |
| } | |
| for (const k of kids.flat(Infinity)) if (k != null && k !== false) n.append(k.nodeType ? k : String(k)); | |
| return n; | |
| }; | |
| const icon = (d, cls) => el("svg", { viewBox: "0 0 24 24", "aria-hidden": "true", class: cls }, el("path", { d })); | |
| const CHEVRON = "M9 6l6 6-6 6"; | |
| const CROSS = "M6 6l12 12M18 6L6 18"; | |
| const LINK = "M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"; | |
| const DOWNLOAD = "M12 4v11M7 10l5 5 5-5M5 19h14"; | |
| const TERMINAL = "M5 7l4 4-4 4M11 16h8"; | |
| const EXTERNAL = "M14 5h5v5M19 5l-8 8M18 14v5H5V6h5"; | |
| const FFLATE = "https://cdn.jsdelivr.net/npm/fflate@0.8.2/esm/browser.js"; | |
| const EXPAND = "M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"; | |
| const COLLAPSE = "M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5"; | |
| let DATA = null; | |
| // material: the chosen option of the open asset's "Material" variant set (null = its default) | |
| const state = { q: "", group: null, category: null, facets: {}, sort: "name", asset: null, material: null, open: new Set() }; | |
| // ---- formatting --------------------------------------------------------------- | |
| function maxDim(a) { return a.extents ? Math.max(...a.extents) : 0; } | |
| function volume(a) { return a.extents ? a.extents.reduce((x, y) => x * y, 1) : 0; } | |
| function fmtLen(m) { return m >= 1 ? `${m.toFixed(2)} m` : m >= 0.01 ? `${(m * 100).toFixed(1)} cm` : `${(m * 1000).toFixed(1)} mm`; } | |
| function fmtDims(a) { | |
| if (!a.extents) return "—"; | |
| const metres = maxDim(a) >= 1; | |
| const f = (v) => metres ? v.toFixed(2) : (v * 100).toFixed(1); | |
| return `${a.extents.map(f).join(" × ")} ${metres ? "m" : "cm"}`; | |
| } | |
| function fmtMass(kg) { | |
| if (kg == null) return "—"; | |
| return kg < 1 ? `${+(kg * 1000).toPrecision(3)} g` : `${+kg.toPrecision(4)} kg`; | |
| } | |
| function fmtRange(j) { | |
| if (j.lower == null || j.upper == null || Math.abs(j.upper - j.lower) > 1e6) return j.type === "hinge" ? "spins freely" : "free"; | |
| if (j.type === "hinge") return `${Math.round(j.lower)}° to ${Math.round(j.upper)}°`; | |
| return `${fmtLen(Math.abs(j.upper - j.lower))} travel`; | |
| } | |
| const fmtValue = (type, v) => type === "hinge" ? `${Math.round(v)}°` : fmtLen(Math.abs(v)).replace(/^/, v < 0 ? "−" : ""); | |
| const partsLabel = (a) => a.joints.length ? `${a.joints.length} moving part${a.joints.length > 1 ? "s" : ""}` : "Rigid"; | |
| const cap = (s) => s ? s[0].toUpperCase() + s.slice(1) : s; | |
| // ---- thumbnail background --------------------------------------------------------- | |
| // The page is always dark. The header switch only picks which Isaac renders the cards | |
| // show: the grey studio (default) or the dark floor. Saved per browser as "thumbs". | |
| function thumbMode() { return document.documentElement.dataset.thumbs === "dark" ? "dark" : "grey"; } | |
| function applyThumbMode() { | |
| const m = thumbMode(); | |
| $("thumbs-toggle").setAttribute("aria-label", `Thumbnail background: ${m}. Switch to ${m === "dark" ? "grey" : "dark"}`); | |
| } | |
| // ---- urls --------------------------------------------------------------------- | |
| function fileUrl(a, path) { return `${HF}/datasets/${DATA.dataset}/resolve/${DATA.commit}/${a.id}/${path}`; } | |
| // 640 px Isaac Sim renders from this Space (tools/isaac_thumbs.py), one per thumbnail mode: | |
| // previews/thumbs-light/ on the grey studio floor, previews/thumbs/ on the dark card colour. | |
| // The dataset's 256 px package thumbnail is the fallback. | |
| function thumbUrl(a, mode) { | |
| const rev = `?v=${encodeURIComponent((a.version || "") + "-" + (DATA.thumbs_rev || ""))}`; | |
| if (mode === "grey" && a.thumb_light) return signed(`previews/thumbs-light/${a.id}.webp${rev}`); | |
| if (a.thumb) return signed(`previews/thumbs/${a.id}.webp${rev}`); | |
| const suffix = mode === "grey" ? "_light" : ""; | |
| return fileUrl(a, `simready_usd/.thumbs/256x256/${a.id}.usd${suffix}.png`); | |
| } | |
| // ---- filtering ---------------------------------------------------------------- | |
| function matchesQuery(a, words) { | |
| if (!words.length) return true; | |
| const hay = a._hay || (a._hay = [a.id, a.name, a.class, a.category, a.group, a.summary || "", ...a.joints.map((j) => `${j.name} ${j.type}`), | |
| ...(a.materials ? a.materials.options.map((o) => o.id) : [])] | |
| .join(" ").toLowerCase().replace(/_/g, " ")); | |
| return words.every((w) => hay.includes(w)); | |
| } | |
| function facetPass(a, skipKey) { | |
| for (const f of FACETS) { | |
| if (f.key === skipKey) continue; | |
| const on = state.facets[f.key]; | |
| if (!on || !on.size) continue; | |
| if (!f.options.some(([v, , test]) => on.has(v) && test(a))) return false; | |
| } | |
| return true; | |
| } | |
| function libraryPass(a) { | |
| if (state.category) return a.category === state.category; | |
| if (state.group) return a.group === state.group; | |
| return true; | |
| } | |
| function words() { return state.q.toLowerCase().replace(/_/g, " ").split(/\s+/).filter(Boolean); } | |
| function filtered() { | |
| const w = words(); | |
| const list = DATA.assets.filter((a) => libraryPass(a) && facetPass(a) && matchesQuery(a, w)); | |
| const by = { | |
| name: (x, y) => x.name.localeCompare(y.name), | |
| newest: (x, y) => (y.version || "").localeCompare(x.version || "") || x.name.localeCompare(y.name), | |
| "mass-desc": (x, y) => (y.mass || 0) - (x.mass || 0), | |
| "mass-asc": (x, y) => (x.mass || 0) - (y.mass || 0), | |
| "size-desc": (x, y) => volume(y) - volume(x), | |
| "parts-desc": (x, y) => y.joints.length - x.joints.length || x.name.localeCompare(y.name), | |
| }[state.sort] || ((x, y) => x.name.localeCompare(y.name)); | |
| return list.sort(by); | |
| } | |
| // ---- library ------------------------------------------------------------------ | |
| // A group row selects the group on first click; clicking the selected group again | |
| // collapses or expands it. The caret always just collapses or expands. | |
| function renderLibrary() { | |
| const w = words(); | |
| const pool = DATA.assets.filter((a) => facetPass(a) && matchesQuery(a, w)); | |
| const ul = $("library"); | |
| ul.replaceChildren(); | |
| const all = !state.group && !state.category; | |
| ul.append(el("li", {}, el("button", { class: "lib-row", type: "button", "aria-current": all ? "true" : "false", onclick: () => select(null, null) }, | |
| el("span", { class: "spacer" }), "All assets", el("span", { class: "n" }, pool.length)))); | |
| for (const g of DATA.groups) { | |
| if (!DATA.assets.some((a) => a.group === g)) continue; | |
| const open = state.open.has(g); | |
| const inGroup = pool.filter((a) => a.group === g); | |
| const current = state.group === g && !state.category; | |
| const toggle = (e) => { e.stopPropagation(); open ? state.open.delete(g) : state.open.add(g); renderLibrary(); }; | |
| const li = el("li", {}, el("button", { | |
| class: "lib-row", type: "button", "aria-current": current ? "true" : "false", "aria-expanded": open ? "true" : "false", | |
| onclick: () => { | |
| if (current) { open ? state.open.delete(g) : state.open.add(g); renderLibrary(); } | |
| else { state.open.add(g); select(g, null); } | |
| }, | |
| }, el("span", { class: "caret", onclick: toggle }, icon(CHEVRON)), g, el("span", { class: "n" }, inGroup.length))); | |
| if (open) { | |
| const cats = [...new Set(DATA.assets.filter((a) => a.group === g).map((a) => a.category))].sort(); | |
| li.append(el("ul", { class: "lib-sub" }, cats.map((c) => el("li", {}, el("button", { | |
| class: "lib-row", type: "button", "aria-current": state.category === c ? "true" : "false", onclick: () => select(g, c), | |
| }, cap(c), el("span", { class: "n" }, inGroup.filter((a) => a.category === c).length)))))); | |
| } | |
| ul.append(li); | |
| } | |
| } | |
| function renderFacets() { | |
| const w = words(); | |
| const box = $("facets"); | |
| box.replaceChildren(); | |
| for (const f of FACETS) { | |
| const base = DATA.assets.filter((a) => libraryPass(a) && facetPass(a, f.key) && matchesQuery(a, w)); | |
| const on = state.facets[f.key] || new Set(); | |
| box.append(el("div", { class: "facet" }, el("h3", {}, f.title), el("div", { class: "facet-opts" }, | |
| f.options.map(([v, label, test]) => { | |
| const n = base.filter(test).length; | |
| return el("button", { | |
| class: "opt", type: "button", "aria-pressed": on.has(v) ? "true" : "false", disabled: !n && !on.has(v), | |
| onclick: () => toggleFacet(f.key, v), | |
| }, label, el("span", { class: "n" }, n)); | |
| })))); | |
| } | |
| $("reset").hidden = !(Object.values(state.facets).some((s) => s.size) || state.q || state.group); | |
| } | |
| function renderChips() { | |
| const chips = $("chips"); | |
| chips.replaceChildren(); | |
| const chip = (label, onclear) => el("span", { class: "chip" }, label, | |
| el("button", { type: "button", "aria-label": `Remove ${label}`, onclick: onclear }, icon(CROSS))); | |
| if (state.category) chips.append(chip(cap(state.category), () => select(state.group, null))); | |
| else if (state.group) chips.append(chip(state.group, () => select(null, null))); | |
| for (const f of FACETS) for (const v of state.facets[f.key] || []) { | |
| const opt = f.options.find((o) => o[0] === v); | |
| if (opt) chips.append(chip(opt[1], () => toggleFacet(f.key, v))); | |
| } | |
| } | |
| function renderGrid() { | |
| const list = filtered(); | |
| const n = DATA.assets.length; | |
| $("count").replaceChildren(el("strong", {}, list.length), list.length === n ? " assets" : ` of ${n} assets`); | |
| $("empty").hidden = list.length > 0; | |
| const mode = thumbMode(); | |
| $("grid").replaceChildren(...list.map((a) => el("li", {}, el("button", { | |
| class: "card", type: "button", "aria-current": state.asset === a.id ? "true" : "false", | |
| onclick: () => openAsset(a.id), "data-id": a.id, | |
| }, | |
| el("div", { class: "thumb" }, | |
| el("img", { src: thumbUrl(a, mode), alt: "", loading: "lazy", decoding: "async", width: 640, height: 640, class: a.kind === "scene" ? "cover" : null }), | |
| el("div", { class: "badges" }, el("span", { class: "badge" }, a.kind === "scene" ? "scene" : | |
| a.joints.length ? `${a.joints.length} moving part${a.joints.length > 1 ? "s" : ""}` : "rigid"))), | |
| el("div", { class: "card-text" }, | |
| el("span", { class: "card-name" }, a.name), | |
| el("span", { class: "card-meta" }, a.kind === "scene" ? `${a.objects} objects · ${fmtDims(a)}` : `${cap(a.class || a.category)} · ${fmtMass(a.mass)}`)))))); | |
| } | |
| // ---- detail + 3D viewer ------------------------------------------------------- | |
| let viewer = null, viewerFailed = null, loadedId = null, rigState = []; | |
| async function getViewer() { | |
| if (viewer || viewerFailed) return viewer; | |
| try { | |
| const { createViewer } = await import(signed("./viewer.js?v=34")); | |
| viewer = createViewer(); | |
| } catch (e) { | |
| console.error("3D viewer failed to start", e); | |
| viewerFailed = String((e && e.message) || e).slice(0, 160); | |
| } | |
| return viewer; | |
| } | |
| function fmtBytes(n) { | |
| if (!n) return ""; | |
| const units = ["B", "KB", "MB", "GB"]; | |
| let i = 0; | |
| while (n >= 1000 && i < units.length - 1) { n /= 1000; i++; } | |
| return `${n.toFixed(i >= 2 ? 1 : 0)} ${units[i]}`; | |
| } | |
| function saveBlob(blob, name) { | |
| const url = URL.createObjectURL(blob); | |
| const link = el("a", { href: url, download: name }); | |
| document.body.append(link); | |
| link.click(); | |
| link.remove(); | |
| setTimeout(() => URL.revokeObjectURL(url), 60000); | |
| } | |
| // Download: the asset's package folder (USD, MDL materials, textures, packaging json), | |
| // fetched from the dataset at the catalog's commit and zipped in the browser (stored, not | |
| // recompressed: textures are already compressed). Same files as the hf download command | |
| // minus the .metadata reports. | |
| async function downloadZip(a, button) { | |
| const label = button.querySelector(".dl-label"); | |
| const say = (t) => { label.textContent = t; }; | |
| button.disabled = true; | |
| try { | |
| const rev = DATA.commit || "main"; | |
| const listing = await fetch(`${HF}/api/datasets/${DATA.dataset}/tree/${rev}/${encodeURIComponent(a.id)}?recursive=true`); | |
| if (!listing.ok) throw new Error(`file list: HTTP ${listing.status}`); | |
| // .metadata/ holds validation and benchmark reports, not needed to use the asset | |
| const files = (await listing.json()).filter((f) => f.type === "file" && !f.path.includes("/.metadata/")); | |
| const total = files.reduce((n, f) => n + (f.size || 0), 0) || 1; | |
| const out = {}; | |
| let got = 0, next = 0; | |
| say("Downloading 0%"); | |
| await Promise.all(Array.from({ length: Math.min(4, files.length) }, async () => { | |
| while (next < files.length) { | |
| const f = files[next++]; | |
| const res = await fetch(`${HF}/datasets/${DATA.dataset}/resolve/${rev}/${f.path.split("/").map(encodeURIComponent).join("/")}`); | |
| if (!res.ok) throw new Error(`${f.path}: HTTP ${res.status}`); | |
| const bytes = new Uint8Array(await res.arrayBuffer()); | |
| out[f.path] = bytes; | |
| got += f.size || bytes.length; | |
| say(`Downloading ${Math.min(99, Math.round((got / total) * 100))}%`); | |
| } | |
| })); | |
| say("Zipping…"); | |
| const { zip } = await import(FFLATE); | |
| const data = await new Promise((ok, fail) => zip(out, { level: 0 }, (err, d) => (err ? fail(err) : ok(d)))); | |
| saveBlob(new Blob([data], { type: "application/zip" }), `${a.id}.zip`); | |
| say("Downloaded"); | |
| } catch (e) { | |
| console.error("Download failed", e); | |
| say("Download failed"); | |
| } | |
| setTimeout(() => { say("Download"); button.disabled = false; }, 2500); | |
| } | |
| // Fixed bar under the details (like NVIDIA SimReady Central): Copy URL, and Download with a | |
| // menu for the other ways to get the files. | |
| function renderFoot(a) { | |
| const foot = $("detail-foot"); | |
| if (!a) { foot.replaceChildren(); return; } | |
| const scene = a.kind === "scene"; | |
| const cmd = scene | |
| ? `hf download ${a.scene_dataset} --repo-type dataset --include "scenes/${a.scene}/*" --local-dir scenes-and-worlds` | |
| : `hf download ${DATA.dataset} --repo-type dataset --include "${a.id}/*" --local-dir simready-assets`; | |
| const folder = scene ? `${HF}/datasets/${a.scene_dataset}/tree/main/scenes/${a.scene}` | |
| : `${HF}/datasets/${DATA.dataset}/tree/main/${a.id}`; | |
| const copy = el("button", { class: "btn foot-copy", type: "button" }, icon(LINK), el("span", {}, "Copy URL")); | |
| copy.addEventListener("click", async () => { | |
| const text = copy.querySelector("span"); | |
| try { await navigator.clipboard.writeText(shareUrl()); text.textContent = "Copied"; } | |
| catch { text.textContent = "Copy failed"; } | |
| setTimeout(() => { text.textContent = "Copy URL"; }, 1600); | |
| }); | |
| // Scenes sit in a gated dataset (free access form), so their files can't be fetched here. | |
| const main = scene | |
| ? el("a", { class: "btn primary dl-main", href: folder, target: "_blank", rel: "noopener", | |
| title: "Free: log in to Hugging Face and answer 3 quick questions to get the files" }, | |
| icon(DOWNLOAD), el("span", { class: "dl-label" }, "Download"), el("span", { class: "dl-size" }, "on Hugging Face")) | |
| : el("button", { class: "btn primary dl-main", type: "button", title: "Download the asset with its materials and textures (zip)" }, | |
| icon(DOWNLOAD), el("span", { class: "dl-label" }, "Download"), el("span", { class: "dl-size" }, fmtBytes(a.size))); | |
| if (!scene) main.addEventListener("click", () => downloadZip(a, main)); | |
| const menu = el("div", { class: "dl-menu", role: "menu", hidden: true }); | |
| const caret = el("button", { class: "btn primary dl-caret", type: "button", "aria-label": "More ways to download", | |
| "aria-haspopup": "menu", "aria-expanded": "false" }, icon(CHEVRON)); | |
| const close = () => { menu.hidden = true; caret.setAttribute("aria-expanded", "false"); }; | |
| caret.addEventListener("click", (e) => { | |
| e.stopPropagation(); | |
| menu.hidden = !menu.hidden; | |
| caret.setAttribute("aria-expanded", String(!menu.hidden)); | |
| }); | |
| const cmdItem = el("button", { class: "dl-item", type: "button", role: "menuitem", title: cmd }, icon(TERMINAL), el("span", {}, "Copy hf download command")); | |
| cmdItem.addEventListener("click", async () => { | |
| const text = cmdItem.querySelector("span"); | |
| try { await navigator.clipboard.writeText(cmd); text.textContent = "Copied"; } catch { text.textContent = "Copy failed"; } | |
| setTimeout(() => { text.textContent = "Copy hf download command"; close(); }, 1200); | |
| }); | |
| const zipItem = scene ? null : el("button", { class: "dl-item", type: "button", role: "menuitem" }, icon(DOWNLOAD), el("span", {}, "Download zip")); | |
| if (zipItem) zipItem.addEventListener("click", () => { close(); downloadZip(a, main); }); | |
| menu.append(...[zipItem, cmdItem, | |
| el("a", { class: "dl-item", role: "menuitem", href: folder, target: "_blank", rel: "noopener" }, icon(EXTERNAL), el("span", {}, "Open on Hugging Face")), | |
| ].filter(Boolean)); | |
| foot.replaceChildren(copy, el("div", { class: "dl" }, main, caret), menu); | |
| } | |
| document.addEventListener("click", (e) => { | |
| const menu = document.querySelector(".dl-menu"); | |
| if (menu && !menu.hidden && !e.target.closest(".dl-menu")) { | |
| menu.hidden = true; | |
| document.querySelector(".dl-caret")?.setAttribute("aria-expanded", "false"); | |
| } | |
| }); | |
| // Expanded view: the detail panel fills the window, the 3D view takes the left side and the | |
| // details (sliders, facts, Copy URL / Download) stay in a column on the right, which the | |
| // edge button hides or shows. The same corner button (or Esc) goes back. The viewer keeps | |
| // its state; on the way in it backs up to show the whole model, on the way out the panel | |
| // gets back the camera it had. | |
| const PANEL_HIDE = "M9 6l6 6-6 6", PANEL_SHOW = "M15 6l-6 6 6 6"; | |
| let expanded = null; // { box, view, spot, stage } | |
| function setExpandButton(box, on) { | |
| const b = box.querySelector(".viewer-expand"); | |
| if (!b) return; | |
| b.replaceChildren(icon(on ? COLLAPSE : EXPAND)); | |
| b.setAttribute("aria-label", on ? "Exit full view" : "Expand 3D view"); | |
| b.title = on ? "Exit full view (Esc)" : "Expand"; | |
| } | |
| function expandViewer(box) { | |
| if (!viewer || expanded) return; | |
| const pane = $("detail"); | |
| const spot = document.createComment("viewer"); | |
| box.before(spot); | |
| const toggle = el("button", { class: "panel-toggle", type: "button", "aria-label": "Hide details", title: "Hide details", | |
| "aria-controls": "detail-body" }, icon(PANEL_HIDE)); | |
| toggle.addEventListener("click", () => { | |
| const hidden = pane.classList.toggle("panel-hidden"); | |
| toggle.replaceChildren(icon(hidden ? PANEL_SHOW : PANEL_HIDE)); | |
| toggle.setAttribute("aria-label", hidden ? "Show details" : "Hide details"); | |
| toggle.title = hidden ? "Show details" : "Hide details"; | |
| }); | |
| const stage = el("div", { class: "detail-stage" }, box, toggle); | |
| pane.prepend(stage); | |
| pane.classList.add("expanded"); | |
| document.documentElement.classList.add("viewer-open"); | |
| expanded = { box, view: viewer.getView(), spot, stage }; | |
| setExpandButton(box, true); | |
| requestAnimationFrame(() => viewer.fit()); // after the stage has its size | |
| } | |
| function collapseViewer() { | |
| if (!expanded) return; | |
| const { box, view, spot, stage } = expanded; | |
| expanded = null; | |
| const pane = $("detail"); | |
| pane.classList.remove("expanded", "panel-hidden"); | |
| document.documentElement.classList.remove("viewer-open"); | |
| if (spot.isConnected) spot.replaceWith(box); | |
| stage.remove(); | |
| setExpandButton(box, false); | |
| if (viewer && box.isConnected) { | |
| viewer.resize(); | |
| viewer.setView(view); | |
| box.querySelector(".viewer-expand")?.focus(); | |
| } | |
| } | |
| // Fallback when the 3D view can't run: the package thumbnail. | |
| function imageView(a) { | |
| return el("div", { class: "thumb" }, el("img", { src: thumbUrl(a, thumbMode()), alt: `${a.name} preview` })); | |
| } | |
| function jointRows(a) { | |
| // One row per joint; in 3D view each row gets a slider bound to the viewer. | |
| const list = el("div", { class: "joints" }); | |
| const rows = a.joints.map((j) => { | |
| const out = el("output", {}, `${j.type}, ${fmtRange(j)}`); | |
| const row = el("div", { class: "joint", "data-joint": j.name }, el("div", { class: "joint-head" }, el("code", {}, j.name), out)); | |
| row._out = out; row._joint = j; | |
| list.append(row); | |
| return row; | |
| }); | |
| return { list, rows }; | |
| } | |
| function bindSliders(rows, rig) { | |
| rigState = rig; | |
| rig.forEach((r, i) => { | |
| const row = rows.find((x) => x.dataset.joint === r.name); | |
| if (!row) return; | |
| const step = r.type === "hinge" ? 1 : Math.max((r.hi - r.lo) / 200, 0.0005); | |
| const input = el("input", { type: "range", min: r.lo, max: r.hi, step, value: r.val, "aria-label": `${r.name} position` }); | |
| input.addEventListener("input", () => viewer.setJoint(i, parseFloat(input.value))); | |
| if (r.follows) row.append(el("div", { class: "joint-link" }, r.oneWay ? `Linked: driven by ${r.follows}` : `Linked: moves with ${r.follows}`)); | |
| row.append(input); | |
| row._input = input; | |
| r.row = row; | |
| row._out.textContent = fmtValue(r.type, r.val); | |
| }); | |
| viewer.onJoint((i, v) => { | |
| const r = rigState[i]; | |
| if (!r || !r.row) return; | |
| r.row._input.value = v; | |
| r.row._out.textContent = fmtValue(r.type, v); | |
| }); | |
| } | |
| // ---- material switch ------------------------------------------------------------ | |
| // Assets with a "Material" variant set (the fasteners) list each choice with its preview | |
| // colour, mass and physics values (tools/build_catalog.py). Picking one recolours the 3D | |
| // view and updates the mass and physics rows; the thumbnail stays the default material. | |
| const matName = (id) => cap(id.replace(/_/g, " ")); | |
| function currentMaterial(a) { | |
| const opts = a.materials.options; | |
| return opts.find((o) => o.id === state.material) || opts.find((o) => o.id === a.materials.default) || opts[0]; | |
| } | |
| const lookOf = (a, o) => ({ name: a.materials.look, color: o.color, metallic: o.metallic, roughness: o.roughness }); | |
| function swatchCss(c) { | |
| const srgb = (v) => Math.round(255 * Math.min(1, Math.max(0, v <= 0.0031308 ? 12.92 * v : 1.055 * v ** (1 / 2.4) - 0.055))); | |
| return c ? `rgb(${c.map(srgb).join(", ")})` : "transparent"; | |
| } | |
| function physicsText(o) { | |
| const parts = []; | |
| if (o.density != null) parts.push(`${o.density.toLocaleString("en-US")} kg/m³`); | |
| if (o.static_friction != null) parts.push(`friction ${o.static_friction} static, ${o.dynamic_friction} dynamic`); | |
| if (o.restitution != null) parts.push(`restitution ${o.restitution}`); | |
| return parts.join(" · ") || "—"; | |
| } | |
| function materialPicker(a, onPick) { | |
| const cur = currentMaterial(a); | |
| const buttons = a.materials.options.map((o) => el("button", { | |
| class: "opt mat-opt", type: "button", "aria-pressed": o === cur ? "true" : "false", "data-material": o.id, | |
| onclick: () => onPick(o), | |
| }, el("span", { class: "swatch", style: `background: ${swatchCss(o.color)}` }), matName(o.id))); | |
| const section = el("section", {}, | |
| el("h3", { class: "section-title" }, "Material"), | |
| el("div", { class: "mat-opts", role: "group", "aria-label": "Material" }, buttons), | |
| el("p", { class: "mat-note" }, "A USD variant set (“Material”): the look, mass and friction switch together.")); | |
| section._select = (o) => buttons.forEach((b) => b.setAttribute("aria-pressed", b.dataset.material === o.id ? "true" : "false")); | |
| return section; | |
| } | |
| async function renderDetail() { | |
| const a = state.asset && DATA.assets.find((x) => x.id === state.asset); | |
| const pane = $("detail"); | |
| document.querySelector(".layout").classList.toggle("has-detail", !!a); | |
| pane.hidden = !a; | |
| collapseViewer(); | |
| renderFoot(a); | |
| if (!a) { loadedId = null; return; } | |
| const mode = a.preview && !viewerFailed ? "3d" : "image"; | |
| const box = el("div", { class: "viewer" }); | |
| const bar = el("div", { class: "viewer-bar" }); | |
| const { list: jointList, rows } = jointRows(a); | |
| const jointActions = el("div", { class: "joint-actions" }); | |
| if (mode === "image") { | |
| box.append(imageView(a)); | |
| if (a.preview && viewerFailed) bar.append(el("span", { class: "hint" }, `3D view unavailable: ${viewerFailed}`)); | |
| } else { | |
| bar.append(el("span", { class: "hint" }, a.joints.length | |
| ? "Drag a part to move it · drag empty space to orbit · scroll to zoom · right-drag to pan" | |
| : a.kind === "scene" && !a.splat && a.room !== false ? "Drag to look around · scroll to move in and out · right-drag to pan" | |
| : "Drag to orbit · scroll to zoom · right-drag to pan")); | |
| } | |
| if (bar.childNodes.length) box.append(bar); | |
| const scene = a.kind === "scene"; | |
| const folder = scene ? `${HF}/datasets/${a.scene_dataset}/tree/main/scenes/${a.scene}` : `${HF}/datasets/${DATA.dataset}/tree/main/${a.id}`; | |
| const files = el("a", { href: folder, target: "_blank", rel: "noopener" }, `${scene ? a.scene_dataset : DATA.dataset} ↗`); | |
| const mat = !scene && a.materials ? currentMaterial(a) : null; | |
| const massEl = el("span", {}, fmtMass(mat ? mat.mass : a.mass)); | |
| const physEl = el("span", {}, mat ? physicsText(mat) : ""); | |
| const picker = mat ? materialPicker(a, (o) => { | |
| state.material = o.id === a.materials.default ? null : o.id; | |
| picker._select(o); | |
| massEl.textContent = fmtMass(o.mass); | |
| physEl.textContent = physicsText(o); | |
| if (viewer && loadedId === a.id) viewer.setLook(lookOf(a, o)); | |
| syncUrl(); | |
| }) : null; | |
| const facts = scene ? [ | |
| ["Type", "Indoor scene"], | |
| ["Dimensions", fmtDims(a)], | |
| ["Objects", `${a.objects}, each its own USD asset`], | |
| ["Triangles", a.triangles ? a.triangles.toLocaleString("en-US") : "—"], | |
| ["Backdrop", a.splat ? "Gaussian splat (USDZ) around the room" : a.room === false ? "None: furniture on a floor, no walls" : "Modelled room, no splat"], | |
| ["Format", "OpenUSD scene for NVIDIA Isaac Sim, plus a GLB preview"], | |
| ["License", "CC BY 4.0 · credit “projectsim by Kaedim”"], | |
| ["Files", el("span", {}, files, el("br"), el("span", { class: "note" }, "Free: log in and answer 3 quick questions on the dataset page"))], | |
| ] : [ | |
| ["Class", a.qcode ? el("a", { href: `https://www.wikidata.org/wiki/${a.qcode}`, target: "_blank", rel: "noopener" }, `${a.class || a.qcode} (${a.qcode})`) : a.class], | |
| ["Category", `${a.group} › ${cap(a.category)}`], | |
| ["Dimensions", fmtDims(a)], | |
| ["Mass", massEl], | |
| ["Rigid bodies", a.rigid_bodies], | |
| ["Moving parts", partsLabel(a)], | |
| ["Placement", a.mounted ? "Mounted: base fixed to the world where you place it" : "Free-standing"], | |
| ["Physics", "PhysX (NVIDIA Isaac Sim)"], | |
| mat && ["Physics material", physEl], | |
| ["Format", mat ? `OpenUSD, “Material” variant set with ${a.materials.options.length} materials` | |
| : `OpenUSD${a.glass ? ", glass MDL shaders included" : ""}`], | |
| ["License", "CC BY 4.0 · credit “projectsim by Kaedim”"], | |
| ["Version", a.version], | |
| ["Files", files], | |
| ]; | |
| $("detail-body").replaceChildren(...[ | |
| el("div", {}, | |
| el("div", { class: "detail-head" }, el("h2", {}, a.name), | |
| el("button", { class: "icon-button", type: "button", "aria-label": "Close details", onclick: () => openAsset(null) }, icon(CROSS))), | |
| el("p", { class: "detail-sub" }, scene ? a.summary : `${cap(a.class || a.category)} · ${partsLabel(a)}`)), | |
| box, | |
| picker, | |
| a.joints.length ? el("section", {}, el("h3", { class: "section-title" }, "Moving parts"), jointList, jointActions) : null, | |
| el("dl", { class: "facts" }, facts.filter(Boolean).map(([k, v]) => [el("dt", {}, k), el("dd", {}, v ?? "—")])), | |
| el("section", { class: "more" }, | |
| el("p", {}, el("strong", {}, "Need many variations, or your own objects?")), | |
| el("p", {}, scene ? "projectsim generates sim-ready rooms and the objects in them at scale, with physics set up." | |
| : `projectsim generates sim-ready objects like this ${a.class || "asset"} at scale, with physics and moving parts set up.`), | |
| el("div", { class: "btn-row" }, | |
| el("a", { class: "btn primary", href: API_DOCS, target: "_blank", rel: "noopener" }, "Generate with the API"), | |
| el("a", { class: "btn", href: "mailto:team@projectsim.ai" }, "team@projectsim.ai"))), | |
| ].filter(Boolean)); // replaceChildren() would print a null section as the text "null" | |
| $("detail-body").scrollTop = 0; | |
| if (mode !== "3d") return; | |
| const v = await getViewer(); | |
| if (!v) { renderDetail(); return; } | |
| if (state.asset !== a.id) return; | |
| box.prepend(v.element); | |
| v.resize(); | |
| box.append(el("button", { class: "viewer-expand", type: "button", "aria-label": "Expand 3D view", title: "Expand", | |
| onclick: () => (expanded ? collapseViewer() : expandViewer(box)) }, icon(EXPAND))); | |
| let rig; | |
| if (loadedId === a.id && rigState.length) { | |
| rig = rigState.map((r) => ({ ...r })); | |
| } else { | |
| loadedId = a.id; | |
| rig = scene ? await v.load(signed(`previews/scenes/${a.scene}.glb`), null, { interior: !a.splat && a.room !== false, enclosed: !a.splat && a.room !== false }) | |
| : await v.load(signed(`previews/${a.id}.glb`), signed(`previews/${a.id}.json`), mat ? { look: lookOf(a, currentMaterial(a)) } : {}); | |
| if (state.asset !== a.id) return; | |
| } | |
| if (mat) v.setLook(lookOf(a, currentMaterial(a))); // also after a click made while it loaded | |
| if (rig.length) { | |
| bindSliders(rows, rig); | |
| jointActions.append( | |
| el("button", { class: "btn small", type: "button", onclick: () => v.openJoints() }, "Open all"), | |
| el("button", { class: "btn small", type: "button", onclick: () => v.resetJoints() }, "Reset")); | |
| } | |
| } | |
| // ---- state + url -------------------------------------------------------------- | |
| // Only our own keys are rewritten: a private Space's page URL also carries a signed | |
| // access token (__sign), and every later request for files of this Space needs it. | |
| const OWN_KEYS = ["q", "g", "c", "sort", "a", "m", ...FACETS.map((f) => f.key)]; | |
| function ownParams() { | |
| const p = new URLSearchParams(); | |
| if (state.q) p.set("q", state.q); | |
| if (state.group) p.set("g", state.group); | |
| if (state.category) p.set("c", state.category); | |
| for (const [k, s] of Object.entries(state.facets)) if (s.size) p.set(k, [...s].join(",")); | |
| if (state.sort !== "name") p.set("sort", state.sort); | |
| if (state.asset) p.set("a", state.asset); | |
| if (state.asset && state.material) p.set("m", state.material); | |
| return p; | |
| } | |
| function syncUrl() { | |
| const p = new URLSearchParams(location.search); | |
| OWN_KEYS.forEach((k) => p.delete(k)); | |
| for (const [k, v] of ownParams()) p.set(k, v); | |
| const qs = p.toString(); | |
| history.replaceState(null, "", qs ? `?${qs}` : location.pathname); | |
| } | |
| // Link to share: the Space page on huggingface.co (never the signed hf.space URL). | |
| function shareUrl() { | |
| const qs = ownParams().toString(); | |
| const base = /\.hf\.space$/.test(location.hostname) ? SPACE_URL : location.origin + location.pathname; | |
| return qs ? `${base}?${qs}` : base; | |
| } | |
| function readUrl() { | |
| const p = new URLSearchParams(location.search); | |
| state.q = p.get("q") || ""; | |
| state.group = p.get("g"); | |
| state.category = p.get("c"); | |
| state.sort = p.get("sort") || "name"; | |
| state.asset = p.get("a"); | |
| state.material = p.get("m"); | |
| for (const f of FACETS) if (p.get(f.key)) state.facets[f.key] = new Set(p.get(f.key).split(",")); | |
| if (state.group) state.open.add(state.group); | |
| } | |
| function refresh() { renderLibrary(); renderFacets(); renderChips(); renderGrid(); syncUrl(); } | |
| function select(group, category) { state.group = group; state.category = category; refresh(); closeSideOnPhone(); } | |
| function toggleFacet(key, v) { | |
| const s = state.facets[key] || (state.facets[key] = new Set()); | |
| s.has(v) ? s.delete(v) : s.add(v); | |
| refresh(); | |
| } | |
| function openAsset(id) { | |
| if (id !== state.asset) state.material = null; | |
| state.asset = id; | |
| renderDetail(); | |
| document.querySelectorAll(".card").forEach((c) => c.setAttribute("aria-current", c.dataset.id === id ? "true" : "false")); | |
| syncUrl(); | |
| } | |
| function closeSideOnPhone() { | |
| if (window.matchMedia("(max-width: 900px)").matches) { $("side").classList.remove("open"); $("filters-toggle").setAttribute("aria-expanded", "false"); } | |
| } | |
| async function start() { | |
| applyThumbMode(); | |
| try { | |
| DATA = await (await fetch("data/catalog.json", { cache: "no-cache" })).json(); | |
| } catch { | |
| $("count").textContent = "The catalog didn't load. Refresh the page to try again."; | |
| return; | |
| } | |
| readUrl(); | |
| $("q").value = state.q; | |
| $("sort").value = state.sort; | |
| $("built").textContent = `${DATA.assets.length} assets · updated ${DATA.built.slice(0, 10)}`; | |
| let t; | |
| $("q").addEventListener("input", (e) => { clearTimeout(t); t = setTimeout(() => { state.q = e.target.value.trim(); refresh(); }, 120); }); | |
| $("sort").addEventListener("change", (e) => { state.sort = e.target.value; refresh(); }); | |
| $("reset").addEventListener("click", () => { state.q = ""; $("q").value = ""; state.group = state.category = null; state.facets = {}; refresh(); }); | |
| $("filters-toggle").addEventListener("click", () => { | |
| const open = $("side").classList.toggle("open"); | |
| $("filters-toggle").setAttribute("aria-expanded", open ? "true" : "false"); | |
| }); | |
| $("thumbs-toggle").addEventListener("click", () => { | |
| const next = thumbMode() === "dark" ? "grey" : "dark"; | |
| if (next === "dark") document.documentElement.dataset.thumbs = "dark"; | |
| else delete document.documentElement.dataset.thumbs; | |
| try { localStorage.setItem("thumbs", next); } catch (e) { /* private mode: lasts this visit */ } | |
| applyThumbMode(); | |
| renderGrid(); | |
| if (viewerFailed) renderDetail(); | |
| }); | |
| document.addEventListener("keydown", (e) => { | |
| if (e.key === "Escape") { if (expanded) collapseViewer(); else if (state.asset) openAsset(null); else closeSideOnPhone(); } | |
| if (e.key === "/" && document.activeElement !== $("q")) { e.preventDefault(); $("q").focus(); } | |
| }); | |
| refresh(); | |
| renderDetail(); | |
| } | |
| start(); | |