Datasets:
Download viewer/app.js from codepawl/scanned-objects-glb: direct link, hf CLI and curl.
- Browser
- Download file 12.4 kB
-
https://huggingface.co/datasets/codepawl/scanned-objects-glb/resolve/main/viewer/app.js
- Command line
-
hf download hf://datasets/codepawl/scanned-objects-glb/viewer/app.js
-
curl -L -o app.js https://huggingface.co/datasets/codepawl/scanned-objects-glb/resolve/main/viewer/app.js
12.4 kB
| // Browse the codepawl/scanned-objects-glb dataset and orbit any object. Thumbnails and glb files load from the dataset. | |
| // ?base=<url> points at another copy of the dataset files. Served from a local copy of the pack, it reads the files | |
| // next to the viewer folder. | |
| import * as THREE from 'three'; | |
| import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'; | |
| import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; | |
| import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js'; | |
| import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js'; | |
| const DATASET_BASE = 'https://huggingface.co/datasets/codepawl/scanned-objects-glb/resolve/main/'; | |
| const SOURCE_BASE = 'https://app.gazebosim.org/GoogleResearch/fuel/models/'; | |
| const isLocalCopy = ['localhost', '127.0.0.1', '[::1]'].includes(location.hostname); | |
| const fileBase = new URLSearchParams(location.search).get('base') ?? (isLocalCopy ? '../' : DATASET_BASE); | |
| const PAGE_SIZE = 120; | |
| const elements = { | |
| browse: document.getElementById('browse'), | |
| detail: document.getElementById('detail'), | |
| query: document.getElementById('query'), | |
| category: document.getElementById('category'), | |
| count: document.getElementById('count'), | |
| grid: document.getElementById('grid'), | |
| sentinel: document.getElementById('sentinel'), | |
| empty: document.getElementById('empty'), | |
| canvas: document.getElementById('view'), | |
| stageStatus: document.getElementById('stage-status'), | |
| assetName: document.getElementById('asset-name'), | |
| assetCategory: document.getElementById('asset-category'), | |
| ratioValue: document.getElementById('ratio-value'), | |
| stats: document.getElementById('stats'), | |
| download: document.getElementById('download'), | |
| downloadLabel: document.getElementById('download-label'), | |
| copyCode: document.getElementById('copy-code'), | |
| copyLabel: document.getElementById('copy-label'), | |
| sourceLink: document.getElementById('source-link'), | |
| }; | |
| // ---------- data ---------- | |
| // One row per object: [id, name, category, brand, sizeX, sizeY, sizeZ, triangles, sourceBytes, bytes, massKg]. | |
| function toObject(row) { | |
| const [id, name, category, brand, sizeX, sizeY, sizeZ, triangles, sourceBytes, bytes, massKg] = row; | |
| return { | |
| id, name, category, brand, size: [sizeX, sizeY, sizeZ], triangles, sourceBytes, bytes, massKg, | |
| searchText: `${id} ${name} ${category} ${brand ?? ''}`.toLowerCase().replaceAll('_', ' '), | |
| }; | |
| } | |
| const objects = (await (await fetch('./objects.json')).json()).map(toObject); | |
| const objectsById = new Map(objects.map((object) => [object.id, object])); | |
| function formatBytes(bytes) { | |
| if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(1)} GB`; | |
| if (bytes >= 1e6) return `${(bytes / 1e6).toFixed(1)} MB`; | |
| return `${Math.max(1, Math.round(bytes / 1e3))} KB`; | |
| } | |
| function formatSize(size) { | |
| const centimetres = [...size].sort((first, second) => second - first).map((value) => value * 100); | |
| return `${centimetres.map((value) => (value >= 10 ? value.toFixed(0) : value.toFixed(1))).join(' × ')} cm`; | |
| } | |
| const numberFormat = new Intl.NumberFormat('en-US'); | |
| function capitalize(text) { | |
| return text.charAt(0).toUpperCase() + text.slice(1); | |
| } | |
| function fileUrl(path) { | |
| return `${fileBase}${path}`; | |
| } | |
| function modelPath(object) { | |
| const encoded = encodeURIComponent(object.id); | |
| return `objects/${encoded}/${encoded}.glb`; | |
| } | |
| // ---------- browse ---------- | |
| function fillCategories() { | |
| const counts = new Map(); | |
| for (const object of objects) counts.set(object.category, (counts.get(object.category) ?? 0) + 1); | |
| const sorted = [...counts.entries()].sort((first, second) => second[1] - first[1] || first[0].localeCompare(second[0])); | |
| const options = ['<option value="">All categories</option>']; | |
| for (const [category, count] of sorted) options.push(`<option value="${category}">${capitalize(category)} (${count})</option>`); | |
| elements.category.innerHTML = options.join(''); | |
| } | |
| let filtered = objects; | |
| let shownCount = 0; | |
| function applyFilters() { | |
| const terms = elements.query.value.trim().toLowerCase().split(/\s+/).filter(Boolean); | |
| const category = elements.category.value; | |
| filtered = objects.filter((object) => (!category || object.category === category) | |
| && terms.every((term) => object.searchText.includes(term))); | |
| elements.count.textContent = `${numberFormat.format(filtered.length)} objects`; | |
| elements.empty.hidden = filtered.length > 0; | |
| elements.grid.replaceChildren(); | |
| shownCount = 0; | |
| showMore(); | |
| } | |
| function makeTile(object) { | |
| const item = document.createElement('li'); | |
| item.className = 'tile'; | |
| const link = document.createElement('a'); | |
| link.href = `#/m/${encodeURIComponent(object.id)}`; | |
| link.title = object.name; | |
| const image = document.createElement('img'); | |
| image.className = 'thumb'; | |
| image.loading = 'lazy'; | |
| image.alt = object.name; | |
| image.src = fileUrl(`thumbs/${encodeURIComponent(object.id)}.webp`); | |
| const meta = document.createElement('div'); | |
| meta.className = 'tile-meta'; | |
| const name = document.createElement('span'); | |
| name.className = 'tile-name'; | |
| name.textContent = object.name; | |
| const size = document.createElement('span'); | |
| size.className = 'tile-size'; | |
| size.textContent = formatBytes(object.bytes); | |
| meta.append(name, size); | |
| link.append(image, meta); | |
| item.append(link); | |
| return item; | |
| } | |
| function showMore() { | |
| const next = filtered.slice(shownCount, shownCount + PAGE_SIZE); | |
| elements.grid.append(...next.map(makeTile)); | |
| shownCount += next.length; | |
| } | |
| new IntersectionObserver((entries) => { | |
| if (entries.some((entry) => entry.isIntersecting) && shownCount < filtered.length && !elements.browse.hidden) showMore(); | |
| }, { rootMargin: '800px' }).observe(elements.sentinel); | |
| elements.query.addEventListener('input', applyFilters); | |
| elements.category.addEventListener('change', applyFilters); | |
| // ---------- 3D view ---------- | |
| let viewer = null; | |
| function createViewer() { | |
| const renderer = new THREE.WebGLRenderer({ canvas: elements.canvas, antialias: true, alpha: true }); | |
| renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); | |
| renderer.toneMapping = THREE.ACESFilmicToneMapping; | |
| renderer.setClearColor(0x000000, 0); | |
| const scene = new THREE.Scene(); | |
| scene.environment = new THREE.PMREMGenerator(renderer).fromScene(new RoomEnvironment(), 0.04).texture; | |
| const keyLight = new THREE.DirectionalLight(0xfff2e0, 1.4); | |
| keyLight.position.set(3.5, 5.5, 4.5); | |
| scene.add(keyLight); | |
| const camera = new THREE.PerspectiveCamera(30, 1, 0.01, 1000); | |
| const controls = new OrbitControls(camera, elements.canvas); | |
| controls.enableDamping = true; | |
| const loader = new GLTFLoader().setMeshoptDecoder(MeshoptDecoder); | |
| function resize() { | |
| const { clientWidth, clientHeight } = elements.canvas; | |
| if (clientWidth === 0 || clientHeight === 0) return; | |
| renderer.setSize(clientWidth, clientHeight, false); | |
| camera.aspect = clientWidth / clientHeight; | |
| camera.updateProjectionMatrix(); | |
| } | |
| new ResizeObserver(resize).observe(elements.canvas); | |
| renderer.setAnimationLoop(() => { | |
| if (elements.detail.hidden) return; | |
| controls.update(); | |
| renderer.render(scene, camera); | |
| }); | |
| return { renderer, scene, camera, controls, loader, model: null, loadToken: 0 }; | |
| } | |
| function disposeTree(root) { | |
| root.traverse((node) => { | |
| if (!node.isMesh) return; | |
| node.geometry.dispose(); | |
| node.material.map?.dispose(); | |
| node.material.dispose(); | |
| }); | |
| } | |
| /** Seen from the front-right and a bit above, at a distance that fits the bounding sphere. */ | |
| function frameModel(root) { | |
| const { camera, controls } = viewer; | |
| const box = new THREE.Box3().setFromObject(root); | |
| const sphere = box.getBoundingSphere(new THREE.Sphere()); | |
| const distance = sphere.radius / Math.sin(THREE.MathUtils.degToRad(camera.fov / 2)) * 0.95; | |
| const direction = new THREE.Vector3(Math.sin(0.61) * Math.cos(0.38), Math.sin(0.38), Math.cos(0.61) * Math.cos(0.38)); | |
| camera.position.copy(sphere.center).addScaledVector(direction, distance); | |
| camera.near = sphere.radius / 100; | |
| camera.far = sphere.radius * 100; | |
| camera.updateProjectionMatrix(); | |
| controls.target.copy(sphere.center); | |
| controls.minDistance = sphere.radius * 0.3; | |
| controls.maxDistance = sphere.radius * 8; | |
| controls.update(); | |
| } | |
| const FAILED_ICON = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3 2 20h20L12 3z"/><path d="M12 10v4m0 3h.01"/></svg>'; | |
| function setStageStatus(state, text) { | |
| elements.stageStatus.className = `stage-status ${state}`; | |
| if (state === 'loading') elements.stageStatus.innerHTML = `<span class="spinner"></span><span>${text}</span>`; | |
| else if (state === 'failed') elements.stageStatus.innerHTML = `${FAILED_ICON}<span>${text}</span>`; | |
| else elements.stageStatus.replaceChildren(); | |
| } | |
| async function loadModel(object) { | |
| viewer ??= createViewer(); | |
| const token = ++viewer.loadToken; | |
| if (viewer.model) { | |
| viewer.scene.remove(viewer.model); | |
| disposeTree(viewer.model); | |
| viewer.model = null; | |
| } | |
| setStageStatus('loading', 'Loading'); | |
| try { | |
| const gltf = await viewer.loader.loadAsync(fileUrl(modelPath(object)), (event) => { | |
| if (token !== viewer.loadToken) return; | |
| const total = event.total || object.bytes; | |
| setStageStatus('loading', `Loading ${Math.min(100, Math.round((event.loaded / total) * 100))}%`); | |
| }); | |
| if (token !== viewer.loadToken) { | |
| disposeTree(gltf.scene); | |
| return; | |
| } | |
| viewer.model = gltf.scene; | |
| viewer.scene.add(gltf.scene); | |
| frameModel(gltf.scene); | |
| setStageStatus('done', ''); | |
| } catch (error) { | |
| if (token !== viewer.loadToken) return; | |
| console.error(error); | |
| setStageStatus('failed', 'This object did not load. Try again or download the file.'); | |
| } | |
| } | |
| // ---------- detail page ---------- | |
| function statRow(label, value) { | |
| return `<dt>${label}</dt><dd>${value}</dd>`; | |
| } | |
| function snippetFor(object) { | |
| return [ | |
| "import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';", | |
| "import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';", | |
| '', | |
| 'const loader = new GLTFLoader().setMeshoptDecoder(MeshoptDecoder);', | |
| `loader.load('${DATASET_BASE}${modelPath(object)}', (gltf) => scene.add(gltf.scene));`, | |
| ].join('\n'); | |
| } | |
| let currentObject = null; | |
| function showDetail(object) { | |
| currentObject = object; | |
| document.title = `${object.name} · Scanned Objects GLB`; | |
| elements.assetName.textContent = object.name; | |
| elements.assetCategory.textContent = [capitalize(object.category), object.brand].filter(Boolean).join(' · '); | |
| elements.ratioValue.textContent = `${Math.round(object.sourceBytes / object.bytes)}× smaller`; | |
| elements.stats.innerHTML = [ | |
| statRow('Real size', formatSize(object.size)), | |
| statRow('File size', `<span class="before">${formatBytes(object.sourceBytes)} → </span>${formatBytes(object.bytes)}`), | |
| statRow('Triangles', numberFormat.format(object.triangles)), | |
| statRow('Texture', '<span class="before">4096 px PNG → </span>2048 px WebP'), | |
| statRow('Estimated mass', `${object.massKg.toFixed(2)} kg`), | |
| ].join(''); | |
| elements.download.href = `${fileUrl(modelPath(object))}?download=true`; | |
| elements.downloadLabel.textContent = `Download .glb (${formatBytes(object.bytes)})`; | |
| elements.copyLabel.textContent = 'Copy three.js code'; | |
| elements.sourceLink.href = `${SOURCE_BASE}${encodeURIComponent(object.id)}`; | |
| loadModel(object); | |
| } | |
| elements.copyCode.addEventListener('click', async () => { | |
| if (!currentObject) return; | |
| try { | |
| await navigator.clipboard.writeText(snippetFor(currentObject)); | |
| elements.copyLabel.textContent = 'Copied'; | |
| } catch { | |
| elements.copyLabel.textContent = 'Copy blocked by the browser'; | |
| } | |
| }); | |
| // ---------- routing ---------- | |
| let browseScroll = 0; | |
| function route() { | |
| const match = location.hash.match(/^#\/m\/(.+)$/); | |
| const object = match ? objectsById.get(decodeURIComponent(match[1])) : null; | |
| if (object) { | |
| if (!elements.browse.hidden) browseScroll = window.scrollY; | |
| elements.browse.hidden = true; | |
| elements.detail.hidden = false; | |
| window.scrollTo(0, 0); | |
| showDetail(object); | |
| return; | |
| } | |
| document.title = 'Scanned Objects GLB'; | |
| elements.detail.hidden = true; | |
| elements.browse.hidden = false; | |
| window.scrollTo(0, browseScroll); | |
| } | |
| fillCategories(); | |
| applyFilters(); | |
| window.addEventListener('hashchange', route); | |
| route(); | |
| window.__ready = true; | |