Datasets:
File size: 12,352 Bytes
885ffaa | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 | // 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;
|