File size: 79,732 Bytes
9c890d3 | 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 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 | const sceneRoutes={}, localScenes=["pstudio","show3d"], defaultDataset="pstudio", expectedSamples=2, datasetNames={pstudio:"PStudio",show3d:"Show3D"};
function fillScenes(dataset) {
document.getElementById("dataset-select").value = dataset;
dom.sceneSelect.replaceChildren();
for (const sample of state.collection.filter(value => value.dataset === dataset)) {
const option = document.createElement("option");
option.value = sample.id;
option.textContent = sample.label;
option.title = sample.label;
dom.sceneSelect.appendChild(option);
}
}
document.getElementById("dataset-select").addEventListener("change", event => {
fillScenes(event.target.value);
void loadSelectedScene();
});
// (c) Meta Platforms, Inc. and affiliates. Confidential and proprietary.
const MODES = ["raw", "chain", "map"];
const MODE_INDEX = Object.freeze({raw: 0, chain: 1, map: 2});
const MILLIMETRES_PER_METRE = 1000;
const RADIUS_UNITS_PER_METRE = 10000;
const SEEK_BIAS_SECONDS = 1e-5;
const dom = {
chunkSelect: document.getElementById("chunk-select"),
errorMessage: document.getElementById("error-message"),
errorOverlay: document.getElementById("error-overlay"),
frameOutput: document.getElementById("frame-output"),
identity: document.getElementById("identity"),
inputStatus: document.getElementById("input-status"),
loading: document.getElementById("loading"),
loadingDetail: document.getElementById("loading-detail"),
loadingProgress: document.getElementById("loading-progress"),
loadingTitle: document.getElementById("loading-title"),
playButton: document.getElementById("play-button"),
playIcon: document.getElementById("play-icon"),
playLabel: document.getElementById("play-label"),
provenanceDetails: document.getElementById("provenance-details"),
provenanceSummary: document.getElementById("provenance-summary"),
reportDetails: document.getElementById("report-details"),
resetCamera: document.getElementById("reset-camera"),
retryButton: document.getElementById("retry-button"),
sceneSelect: document.getElementById("scene-select"),
selfTestStatus: document.getElementById("self-test-status"),
sourceVideo: document.getElementById("source-video"),
timeline: document.getElementById("timeline"),
videoFrame: document.getElementById("video-frame"),
windowDetails: document.getElementById("window-details"),
};
const state = {
abortController: null,
assets: null,
camera: null,
chunkEnd: 1,
chunkStart: 0,
frame: 0,
generation: 0,
renderers: [],
scene: null,
scenes: [],
};
function invariant(condition, message) {
if (!condition) {
throw new Error(message);
}
}
function finiteNumber(value, name) {
invariant(Number.isFinite(value), `${name} must be finite`);
return Number(value);
}
function integer(value, name, minimum = 0) {
invariant(Number.isInteger(value) && value >= minimum, `${name} must be an integer >= ${minimum}`);
return value;
}
function json(value) {
return JSON.stringify(value, null, 2);
}
function packedAsset(name) {
window.__TOOLBOX_PACKED__ ??= JSON.parse(document.getElementById("inline-assets").textContent);
const packed = window.__TOOLBOX_PACKED__;
invariant(packed[name], `Missing embedded asset ${name}`);
return packed[name];
}
function assetBytes(name) {
return Uint8Array.from(packedAsset(name).data);
}
function assetUrl(name) {
const asset = packedAsset(name);
const bytes = assetBytes(name);
const chunks = [];
for (let start = 0; start < bytes.length; start += 32768) {
chunks.push(String.fromCharCode(...bytes.subarray(start, start + 32768)));
}
return `data:${asset.type};base64,${btoa(chunks.join(""))}`;
}
function setLoading(title, detail, fraction = 0) {
dom.loading.classList.remove("done");
dom.loadingTitle.textContent = title;
dom.loadingDetail.textContent = detail;
dom.loadingProgress.style.width = `${Math.max(4, Math.min(100, fraction * 100))}%`;
}
function finishLoading() {
dom.loadingProgress.style.width = "100%";
dom.loading.classList.add("done");
}
function errorText(error) {
if (error instanceof Error) {
return error.stack || error.message;
}
return String(error);
}
function showError(error) {
pause();
dom.errorMessage.textContent = errorText(error);
dom.errorOverlay.hidden = false;
dom.retryButton.focus();
console.error(error);
}
function hideError() {
dom.errorOverlay.hidden = true;
}
function copyUint8(view, offset, count, label) {
invariant(offset + count <= view.byteLength, `${label}: truncated uint8 field`);
return new Uint8Array(view.buffer, view.byteOffset + offset, count).slice();
}
function readUint16LE(view, offset, count, scale, label) {
invariant(offset + count * 2 <= view.byteLength, `${label}: truncated uint16 field`);
const result = scale === 1 ? new Uint16Array(count) : new Float32Array(count);
for (let index = 0; index < count; index += 1) {
result[index] = view.getUint16(offset + index * 2, true) * scale;
}
return result;
}
function readInt16LE(view, offset, count, scale, label) {
invariant(offset + count * 2 <= view.byteLength, `${label}: truncated int16 field`);
const result = new Float32Array(count);
for (let index = 0; index < count; index += 1) {
result[index] = view.getInt16(offset + index * 2, true) * scale;
}
return result;
}
function decodeStatic(buffer, count, deathModes, label) {
count = integer(count, `${label}.count`);
deathModes = integer(deathModes, `${label}.deathModes`, 1);
const expected = count * (14 + deathModes * 2);
invariant(buffer.byteLength === expected, `${label}: expected ${expected} decoded bytes, got ${buffer.byteLength}`);
const view = new DataView(buffer);
let offset = 0;
const positions = readInt16LE(view, offset, count * 3, 1 / MILLIMETRES_PER_METRE, `${label}.positions`);
offset += count * 3 * 2;
const birth = readUint16LE(view, offset, count, 1, `${label}.birth`);
offset += count * 2;
const radius = readUint16LE(view, offset, count, 1 / RADIUS_UNITS_PER_METRE, `${label}.radius`);
offset += count * 2;
const death = [];
for (let mode = 0; mode < deathModes; mode += 1) {
death.push(readUint16LE(view, offset, count, 1, `${label}.death[${mode}]`));
offset += count * 2;
}
const colors = copyUint8(view, offset, count * 3, `${label}.colors`);
offset += count * 3;
const originWindow = copyUint8(view, offset, count, `${label}.originWindow`);
offset += count;
invariant(offset === buffer.byteLength, `${label}: unconsumed bytes`);
return {birth, colors, count, death, originWindow, positions, radius};
}
function expectedTrackBytes(windows, includeStart) {
let positionBytes = 0;
let radiusBytes = 0;
let byteBytes = 0;
for (const [index, window] of windows.entries()) {
const n = integer(window.n, `windows[${index}].n`);
const length = integer(window.L, `windows[${index}].L`);
positionBytes += length * n * 3 * 2;
radiusBytes += n * 2;
byteBytes += length * Math.ceil(n / 8) + n * 3 + (includeStart ? n : 0);
}
return {byteBytes, positionBytes, radiusBytes, total: positionBytes + radiusBytes + byteBytes};
}
function decodeDeltaPositions(view, offset, n, length, label) {
const values = length * n * 3;
invariant(offset + values * 2 <= view.byteLength, `${label}: truncated position stream`);
const previous = new Int32Array(n * 3);
const positions = new Float32Array(values);
let cursor = offset;
for (let frame = 0; frame < length; frame += 1) {
const frameOffset = frame * n * 3;
for (let value = 0; value < n * 3; value += 1) {
previous[value] += view.getInt16(cursor, true);
positions[frameOffset + value] = previous[value] / MILLIMETRES_PER_METRE;
cursor += 2;
}
}
return positions;
}
function decodeTrackWindows(buffer, metadata, includeStart, label) {
invariant(Array.isArray(metadata), `${label}: windows metadata must be an array`);
const sizes = expectedTrackBytes(metadata, includeStart);
invariant(buffer.byteLength === sizes.total, `${label}: expected ${sizes.total} decoded bytes, got ${buffer.byteLength}`);
const view = new DataView(buffer);
let positionOffset = 0;
let radiusOffset = sizes.positionBytes;
let byteOffset = sizes.positionBytes + sizes.radiusBytes;
const windows = [];
for (const [index, source] of metadata.entries()) {
const n = source.n;
const length = source.L;
const bytesPerFrame = Math.ceil(n / 8);
const positions = decodeDeltaPositions(view, positionOffset, n, length, `${label}[${index}].positions`);
positionOffset += length * n * 3 * 2;
const radius = readUint16LE(view, radiusOffset, n, 1 / RADIUS_UNITS_PER_METRE, `${label}[${index}].radius`);
radiusOffset += n * 2;
const visibility = copyUint8(view, byteOffset, length * bytesPerFrame, `${label}[${index}].visibility`);
byteOffset += length * bytesPerFrame;
const colors = copyUint8(view, byteOffset, n * 3, `${label}[${index}].colors`);
byteOffset += n * 3;
let liveStart = null;
if (includeStart) {
liveStart = copyUint8(view, byteOffset, n, `${label}[${index}].start`);
byteOffset += n;
}
windows.push({
bytesPerFrame,
colors,
length,
liveStart,
n,
end: source.end,
ownEnd: source.own_end,
positions,
radius,
start: source.start,
visibility,
});
}
invariant(positionOffset === sizes.positionBytes, `${label}: position layout mismatch`);
invariant(radiusOffset === sizes.positionBytes + sizes.radiusBytes, `${label}: radius layout mismatch`);
invariant(byteOffset === buffer.byteLength, `${label}: byte layout mismatch`);
return windows;
}
function visibilityBit(window, localFrame, point) {
const offset = localFrame * window.bytesPerFrame + (point >> 3);
return (window.visibility[offset] & (1 << (point & 7))) !== 0;
}
function crossfadeLayers(windows, frame, currentIndex) {
const current = windows[currentIndex];
const local = frame - current.start;
invariant(local >= 0 && local < current.length, `frame ${frame} is outside current window ${currentIndex}`);
const layers = [{alpha: 1, index: currentIndex, local, window: current}];
if (currentIndex === 0) {
return layers;
}
const previous = windows[currentIndex - 1];
const overlap = previous.end - current.start;
const previousLocal = frame - previous.start;
if (overlap <= 0 || local >= overlap || previousLocal < 0 || previousLocal >= previous.length) {
return layers;
}
const laterAlpha = (local + 1) / (overlap + 1);
return [
{alpha: 1 - laterAlpha, index: currentIndex - 1, local: previousLocal, window: previous},
{...layers[0], alpha: laterAlpha},
];
}
function multipartName(id, kind, part) {
return part === 0 ? `${id}.${kind}.wasm` : `${id}.${kind}.p${part}.wasm`;
}
async function fetchPart(name, signal) {
signal?.throwIfAborted();
return assetBytes(name);
}
async function gunzipMultipart(id, kind, parts, signal, onPart) {
parts = integer(parts, `${kind}.parts`, 1);
invariant(typeof DecompressionStream === "function", "This browser does not support DecompressionStream('gzip')");
const buffers = await Promise.all(Array.from({length: parts}, async (_, part) => {
const name = multipartName(id, kind, part);
const bytes = await fetchPart(name, signal);
onPart(name, bytes.byteLength);
return bytes;
}));
const compressedLength = buffers.reduce((total, bytes) => total + bytes.byteLength, 0);
const compressed = new Uint8Array(compressedLength);
let offset = 0;
for (const bytes of buffers) {
compressed.set(bytes, offset);
offset += bytes.byteLength;
}
invariant(compressed.length >= 2 && compressed[0] === 0x1f && compressed[1] === 0x8b, `${id}.${kind}: payload is not the required gzip stream`);
try {
const stream = new Blob([compressed]).stream().pipeThrough(new DecompressionStream("gzip"));
return await new Response(stream).arrayBuffer();
} catch (error) {
throw new Error(`${id}.${kind}: gzip decompression failed: ${errorText(error)}`);
}
}
function validateScene(scene) {
invariant(scene && typeof scene === "object", "scenes.json entries must be objects");
invariant(typeof scene.id === "string" && scene.id.length > 0, "scene.id must be non-empty");
integer(scene.frames, `${scene.id}.frames`, 1);
finiteNumber(scene.fps, `${scene.id}.fps`);
invariant(scene.fps > 0, `${scene.id}.fps must be positive`);
invariant(typeof scene.video === "string" && scene.video.length > 0, `${scene.id}.video must be non-empty`);
invariant(scene.static && scene.dyn && scene.stable, `${scene.id}: static/dyn/stable metadata is required`);
invariant(scene.stage2_overlap === true, `${scene.id}: schema-3 stage2 overlap must be enabled`);
integer(scene.static.count, `${scene.id}.static.count`);
integer(scene.static.parts, `${scene.id}.static.parts`, 1);
integer(scene.dyn.parts, `${scene.id}.dyn.parts`, 1);
integer(scene.stable.count, `${scene.id}.stable.count`);
integer(scene.stable.parts, `${scene.id}.stable.parts`, 1);
integer(scene.stable.live_parts, `${scene.id}.stable.live_parts`, 1);
invariant(Array.isArray(scene.windows) && scene.windows.length > 0, `${scene.id}.windows must be non-empty`);
invariant(scene.windows.length <= 256, `${scene.id}: uint8 origin-window wire field supports at most 256 windows`);
invariant(Array.isArray(scene.dyn.windows) && scene.dyn.windows.length === scene.windows.length, `${scene.id}: dynamic windows mismatch`);
invariant(Array.isArray(scene.stable.windows) && scene.stable.windows.length === scene.windows.length, `${scene.id}: stable live windows mismatch`);
for (const mode of MODES) {
const entry = scene.modes?.[mode];
invariant(entry && Array.isArray(entry.scale), `${scene.id}.${mode}: scale array is required`);
invariant(entry.scale.length === scene.windows.length, `${scene.id}.${mode}: scale/window count mismatch`);
for (const [index, scale] of entry.scale.entries()) {
invariant(Number.isFinite(scale) && scale > 0, `${scene.id}.${mode}.scale[${index}] must be positive`);
if (mode === "raw") {
invariant(scale === 1, `${scene.id}.raw.scale[${index}] must be exactly unit scale`);
}
}
}
const global = scene.modes?.global;
invariant(global && Array.isArray(global.scale), `${scene.id}.global: scale array is required`);
invariant(global.scale.length === scene.windows.length, `${scene.id}.global: scale/window count mismatch`);
for (const [index, scale] of global.scale.entries()) {
invariant(Number.isFinite(scale) && scale > 0, `${scene.id}.global.scale[${index}] must be positive`);
}
const covered = new Int16Array(scene.frames);
covered.fill(-1);
for (const [index, metadata] of scene.dyn.windows.entries()) {
integer(metadata.start, `${scene.id}.dyn.windows[${index}].start`);
integer(metadata.own_end, `${scene.id}.dyn.windows[${index}].own_end`, 1);
integer(metadata.end, `${scene.id}.dyn.windows[${index}].end`, 1);
invariant(metadata.start < metadata.own_end && metadata.own_end <= metadata.end && metadata.end <= scene.frames, `${scene.id}.dyn.windows[${index}]: invalid owned/predicted range`);
invariant(metadata.L === metadata.end - metadata.start, `${scene.id}.dyn.windows[${index}]: L must equal end-start`);
invariant(scene.windows[index].start === metadata.start, `${scene.id}.windows[${index}]: origin start mismatch`);
if (index > 0) {
const previous = scene.dyn.windows[index - 1];
invariant(previous.own_end === metadata.start, `${scene.id}: adjacent owned ranges do not meet at C${index}`);
invariant(previous.end > metadata.start, `${scene.id}: C${index - 1}/C${index} have no prediction overlap`);
const declared = scene.provenance?.config?.overlap;
if (Number.isInteger(declared)) {
invariant(previous.end - metadata.start === declared, `${scene.id}: C${index - 1}/C${index} overlap differs from config`);
}
}
for (let frame = metadata.start; frame < metadata.own_end; frame += 1) {
invariant(covered[frame] === -1, `${scene.id}: owned ranges overlap at frame ${frame}`);
covered[frame] = index;
}
const live = scene.stable.windows[index];
invariant(live.start === metadata.start && live.own_end === metadata.own_end && live.end === metadata.end && live.L === metadata.L, `${scene.id}.stable.windows[${index}]: predicted range mismatch`);
}
for (let frame = 0; frame < scene.frames; frame += 1) {
invariant(covered[frame] >= 0, `${scene.id}: no owned window for frame ${frame}`);
}
const plan = scene.provenance?.window_plan;
if (Array.isArray(plan)) {
invariant(plan.length === scene.windows.length, `${scene.id}: provenance window plan count mismatch`);
for (const [index, window] of plan.entries()) {
const dynamic = scene.dyn.windows[index];
invariant(window.start === dynamic.start && window.own_end === dynamic.own_end && window.end === dynamic.end, `${scene.id}: provenance window range mismatch at C${index}`);
invariant(Array.isArray(window.slots) && window.slots.length > 0, `${scene.id}: provenance slots missing at C${index}`);
}
}
invariant(Array.isArray(scene.target) && scene.target.length === 3, `${scene.id}.target must have three values`);
finiteNumber(scene.extent, `${scene.id}.extent`);
finiteNumber(scene.fov, `${scene.id}.fov`);
return covered;
}
function transformAboutCenter(x, y, z, center, scale, output, offset) {
output[offset] = center[0] + scale * (x - center[0]);
output[offset + 1] = center[1] + scale * (y - center[1]);
output[offset + 2] = center[2] + scale * (z - center[2]);
}
class GeometryBuilder {
constructor(capacity) {
this.alpha = new Float32Array(capacity);
this.positions = new Float32Array(capacity * 3);
this.radius = new Float32Array(capacity);
this.colors = new Uint8Array(capacity * 3);
this.count = 0;
this.staticCount = 0;
this.liveCount = 0;
this.fading = false;
}
reset() {
this.count = 0;
this.staticCount = 0;
this.liveCount = 0;
this.fading = false;
}
add(x, y, z, radius, colors, colorOffset, alpha = 1) {
const point = this.count;
const offset = point * 3;
invariant(point < this.radius.length, "frame geometry exceeded decoded point capacity");
this.positions[offset] = x;
this.positions[offset + 1] = y;
this.positions[offset + 2] = z;
this.radius[point] = radius;
this.alpha[point] = alpha;
this.colors[offset] = colors[colorOffset];
this.colors[offset + 1] = colors[colorOffset + 1];
this.colors[offset + 2] = colors[colorOffset + 2];
this.count += 1;
}
value() {
return {
alpha: this.alpha.subarray(0, this.count),
colors: this.colors.subarray(0, this.count * 3),
count: this.count,
fading: this.fading,
liveCount: this.liveCount,
positions: this.positions.subarray(0, this.count * 3),
radius: this.radius.subarray(0, this.count),
staticCount: this.staticCount,
};
}
}
class SceneAssets {
constructor(scene, frameWindow, staticBuffer, dynamicBuffer, stableBuffer, liveBuffer) {
this.scene = scene;
this.frameWindow = frameWindow;
this.static = decodeStatic(staticBuffer, scene.static.count, MODES.length, `${scene.id}.static`);
this.dynamic = decodeTrackWindows(dynamicBuffer, scene.dyn.windows, false, `${scene.id}.dyn`);
this.stable = decodeStatic(stableBuffer, scene.stable.count, 1, `${scene.id}.stable`);
this.live = decodeTrackWindows(liveBuffer, scene.stable.windows, true, `${scene.id}.live`);
this.modeStatic = this.precomputeModeStatic();
this.validateDecodedMembership();
const crossfadeCapacity = windows => Math.max(...windows.map((window, index) =>
window.n + (index > 0 && windows[index - 1].end > window.start ? windows[index - 1].n : 0)), 0);
const maximumDynamic = crossfadeCapacity(this.dynamic);
const maximumLive = crossfadeCapacity(this.live);
this.builders = {
raw: new GeometryBuilder(this.static.count + maximumDynamic),
chain: new GeometryBuilder(this.static.count + maximumDynamic),
map: new GeometryBuilder(this.static.count + maximumDynamic),
stable: new GeometryBuilder(this.stable.count + maximumLive),
};
this.cache = new Map();
}
validateDecodedMembership() {
for (let point = 0; point < this.static.count; point += 1) {
invariant(this.static.originWindow[point] < this.scene.windows.length, `${this.scene.id}.static: origin window out of range at point ${point}`);
}
for (const [index, window] of this.live.entries()) {
for (let point = 0; point < window.n; point += 1) {
invariant(window.liveStart[point] < window.length, `${this.scene.id}.live[${index}]: point start outside owned window`);
}
}
}
precomputeModeStatic() {
const result = {};
for (const mode of MODES) {
const positions = new Float32Array(this.static.positions.length);
const radius = new Float32Array(this.static.radius.length);
const scales = this.scene.modes[mode].scale;
for (let point = 0; point < this.static.count; point += 1) {
const offset = point * 3;
const window = this.static.originWindow[point];
const center = this.scene.windows[window].centre;
const scale = scales[window];
transformAboutCenter(
this.static.positions[offset],
this.static.positions[offset + 1],
this.static.positions[offset + 2],
center,
scale,
positions,
offset,
);
radius[point] = this.static.radius[point] * scale;
}
result[mode] = {positions, radius};
}
return result;
}
geometry(mode, frame) {
const cached = this.cache.get(mode);
if (cached?.frame === frame) {
return cached.geometry;
}
const geometry = mode === "stable" ? this.stableGeometry(frame) : this.modeGeometry(mode, frame);
this.cache.set(mode, {frame, geometry});
return geometry;
}
modeGeometry(mode, frame) {
const builder = this.builders[mode];
builder.reset();
const modeIndex = MODE_INDEX[mode];
const transformed = this.modeStatic[mode];
for (let point = 0; point < this.static.count; point += 1) {
if (this.static.birth[point] <= frame && frame < this.static.death[modeIndex][point]) {
const offset = point * 3;
builder.add(
transformed.positions[offset],
transformed.positions[offset + 1],
transformed.positions[offset + 2],
transformed.radius[point],
this.static.colors,
offset,
);
}
}
builder.staticCount = builder.count;
const layers = crossfadeLayers(this.dynamic, frame, this.frameWindow[frame]);
builder.fading = layers.length > 1;
for (const layer of layers) {
const {alpha, index: windowIndex, local, window} = layer;
const center = this.scene.windows[windowIndex].centre;
const scale = this.scene.modes[mode].scale[windowIndex];
const frameOffset = local * window.n * 3;
for (let point = 0; point < window.n; point += 1) {
if (!visibilityBit(window, local, point)) {
continue;
}
const offset = frameOffset + point * 3;
const colorOffset = point * 3;
const output = builder.count * 3;
invariant(builder.count < builder.radius.length, "frame geometry exceeded decoded point capacity");
transformAboutCenter(
window.positions[offset],
window.positions[offset + 1],
window.positions[offset + 2],
center,
scale,
builder.positions,
output,
);
builder.radius[builder.count] = window.radius[point] * scale;
builder.alpha[builder.count] = alpha;
builder.colors[output] = window.colors[colorOffset];
builder.colors[output + 1] = window.colors[colorOffset + 1];
builder.colors[output + 2] = window.colors[colorOffset + 2];
builder.count += 1;
}
}
builder.liveCount = builder.count - builder.staticCount;
return builder.value();
}
stableGeometry(frame) {
const builder = this.builders.stable;
builder.reset();
for (let point = 0; point < this.stable.count; point += 1) {
if (this.stable.birth[point] <= frame && frame < this.stable.death[0][point]) {
const offset = point * 3;
builder.add(
this.stable.positions[offset],
this.stable.positions[offset + 1],
this.stable.positions[offset + 2],
this.stable.radius[point],
this.stable.colors,
offset,
);
}
}
builder.staticCount = builder.count;
const layers = crossfadeLayers(this.live, frame, this.frameWindow[frame]);
builder.fading = layers.length > 1;
for (const {alpha, local, window} of layers) {
const frameOffset = local * window.n * 3;
for (let point = 0; point < window.n; point += 1) {
if (local < window.liveStart[point] || !visibilityBit(window, local, point)) {
continue;
}
const offset = frameOffset + point * 3;
builder.add(
window.positions[offset],
window.positions[offset + 1],
window.positions[offset + 2],
window.radius[point],
window.colors,
point * 3,
alpha,
);
}
}
builder.liveCount = builder.count - builder.staticCount;
return builder.value();
}
}
async function loadSceneAssets(scene, frameWindow, signal) {
const totalParts = scene.static.parts + scene.dyn.parts + scene.stable.parts + scene.stable.live_parts;
let completedParts = 0;
let compressedBytes = 0;
const onPart = (name, bytes) => {
completedParts += 1;
compressedBytes += bytes;
setLoading(
"Loading embedded model points",
`${completedParts}/${totalParts} parts · ${(compressedBytes / 1e6).toFixed(1)} MB · ${name}`,
0.08 + 0.7 * completedParts / totalParts,
);
};
const [staticBuffer, dynamicBuffer, stableBuffer, liveBuffer] = await Promise.all([
gunzipMultipart(scene.id, "static", scene.static.parts, signal, onPart),
gunzipMultipart(scene.id, "dyn", scene.dyn.parts, signal, onPart),
gunzipMultipart(scene.id, "stable", scene.stable.parts, signal, onPart),
gunzipMultipart(scene.id, "live", scene.stable.live_parts, signal, onPart),
]);
setLoading("Decoding little-endian streams", "Validating lengths, visibility bits, deltas, and membership…", 0.84);
await new Promise(resolve => setTimeout(resolve, 0));
return new SceneAssets(scene, frameWindow, staticBuffer, dynamicBuffer, stableBuffer, liveBuffer);
}
function vectorLength(x, y, z) {
return Math.hypot(x, y, z);
}
function normalize3(x, y, z) {
const length = vectorLength(x, y, z) || 1;
return [x / length, y / length, z / length];
}
function lookAt(eye, center, up) {
const z = normalize3(eye[0] - center[0], eye[1] - center[1], eye[2] - center[2]);
const x = normalize3(
up[1] * z[2] - up[2] * z[1],
up[2] * z[0] - up[0] * z[2],
up[0] * z[1] - up[1] * z[0],
);
const y = [
z[1] * x[2] - z[2] * x[1],
z[2] * x[0] - z[0] * x[2],
z[0] * x[1] - z[1] * x[0],
];
return new Float32Array([
x[0], y[0], z[0], 0,
x[1], y[1], z[1], 0,
x[2], y[2], z[2], 0,
-(x[0] * eye[0] + x[1] * eye[1] + x[2] * eye[2]),
-(y[0] * eye[0] + y[1] * eye[1] + y[2] * eye[2]),
-(z[0] * eye[0] + z[1] * eye[1] + z[2] * eye[2]),
1,
]);
}
function perspective(verticalFovRadians, aspect, near, far) {
const focal = 1 / Math.tan(verticalFovRadians / 2);
const range = 1 / (near - far);
return new Float32Array([
focal / aspect, 0, 0, 0,
0, focal, 0, 0,
0, 0, (far + near) * range, -1,
0, 0, 2 * far * near * range, 0,
]);
}
class OrbitCamera {
constructor(onChange) {
this.onChange = onChange;
this.target = [0, 0, 1];
this.extent = 1;
this.distance = 3;
this.yaw = 0;
this.pitch = 0;
}
reset(scene, notify = true) {
this.target = scene.target.map(Number);
this.extent = Math.max(Number(scene.extent) || 1, 0.05);
this.distance = Math.max(this.extent * (Number(scene.orbit_distance_factor) || 2.8), 0.25);
this.yaw = Number(scene.orbit_yaw) || 0;
this.pitch = Number(scene.orbit_pitch) || 0;
if (notify) {
this.onChange();
}
}
orbit(deltaX, deltaY) {
this.yaw -= deltaX * 0.006;
this.pitch = Math.max(-1.42, Math.min(1.42, this.pitch + deltaY * 0.006));
this.onChange();
}
zoom(delta) {
this.distance = Math.max(this.extent * 0.08, Math.min(this.extent * 80, this.distance * Math.exp(delta * 0.001)));
this.onChange();
}
view() {
const cosPitch = Math.cos(this.pitch);
const eye = [
this.target[0] + Math.sin(this.yaw) * cosPitch * this.distance,
this.target[1] + Math.sin(this.pitch) * this.distance,
this.target[2] - Math.cos(this.yaw) * cosPitch * this.distance,
];
// Packed coordinates are OpenCV RDF, so negative world Y is visually up.
return lookAt(eye, this.target, [0, -1, 0]);
}
}
const VERTEX_SHADER = `
attribute vec3 aPosition;
attribute float aRadius;
attribute vec3 aColor;
attribute float aAlpha;
uniform mat4 uProjection;
uniform mat4 uView;
uniform float uFocalPixels;
uniform float uMaxPointSize;
uniform float uMinPointSize;
varying vec3 vColor;
varying float vAlpha;
void main() {
vec4 camera = uView * vec4(aPosition, 1.0);
gl_Position = uProjection * camera;
float depth = max(-camera.z, 0.0001);
gl_PointSize = clamp(2.0 * aRadius * uFocalPixels / depth, uMinPointSize, uMaxPointSize);
vColor = aColor;
vAlpha = aAlpha;
}`;
const FRAGMENT_SHADER = `
precision mediump float;
varying vec3 vColor;
varying float vAlpha;
void main() {
vec2 delta = gl_PointCoord - vec2(0.5);
if (dot(delta, delta) > 0.25) discard;
gl_FragColor = vec4(vColor, vAlpha);
}`;
function compileShader(gl, kind, source) {
const shader = gl.createShader(kind);
invariant(shader, "WebGL could not allocate a shader");
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
const message = gl.getShaderInfoLog(shader);
gl.deleteShader(shader);
throw new Error(`WebGL shader compilation failed: ${message}`);
}
return shader;
}
function createProgram(gl) {
const vertex = compileShader(gl, gl.VERTEX_SHADER, VERTEX_SHADER);
const fragment = compileShader(gl, gl.FRAGMENT_SHADER, FRAGMENT_SHADER);
const program = gl.createProgram();
invariant(program, "WebGL could not allocate a program");
gl.attachShader(program, vertex);
gl.attachShader(program, fragment);
gl.linkProgram(program);
gl.deleteShader(vertex);
gl.deleteShader(fragment);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
const message = gl.getProgramInfoLog(program);
gl.deleteProgram(program);
throw new Error(`WebGL program linking failed: ${message}`);
}
return program;
}
function pointDrawPasses(geometry) {
if (!geometry.fading) {
return geometry.count > 0 ? [{blending: false, count: geometry.count, depthWrite: true, first: 0}] : [];
}
const passes = [];
if (geometry.staticCount > 0) {
passes.push({blending: false, count: geometry.staticCount, depthWrite: true, first: 0});
}
const fadingCount = geometry.count - geometry.staticCount;
if (fadingCount > 0) {
passes.push({blending: true, count: fadingCount, depthWrite: false, first: geometry.staticCount});
}
return passes;
}
class PointRenderer {
constructor(panel, camera, onCameraChange) {
this.panel = panel;
this.mode = panel.dataset.mode;
this.canvas = panel.querySelector("canvas");
this.status = panel.querySelector('[data-role="status"]');
this.scale = panel.querySelector('[data-role="scale"]');
this.camera = camera;
this.onCameraChange = onCameraChange;
this.gl = this.canvas.getContext("webgl", {alpha: false, antialias: true, preserveDrawingBuffer: true});
invariant(this.gl, `WebGL is unavailable for ${this.mode}`);
this.program = createProgram(this.gl);
this.locations = this.getLocations();
this.buffers = {
alpha: this.gl.createBuffer(),
colors: this.gl.createBuffer(),
positions: this.gl.createBuffer(),
radius: this.gl.createBuffer(),
};
invariant(this.buffers.alpha && this.buffers.colors && this.buffers.positions && this.buffers.radius, "WebGL could not allocate point buffers");
this.maxPointSize = Math.min(64, this.gl.getParameter(this.gl.ALIASED_POINT_SIZE_RANGE)[1]);
this.installInteraction();
this.canvas.addEventListener("webglcontextlost", event => {
event.preventDefault();
showError(new Error(`${this.mode}: WebGL context lost`));
});
new ResizeObserver(() => this.onCameraChange()).observe(this.canvas);
}
getLocations() {
const gl = this.gl;
const locations = {
alpha: gl.getAttribLocation(this.program, "aAlpha"),
color: gl.getAttribLocation(this.program, "aColor"),
focalPixels: gl.getUniformLocation(this.program, "uFocalPixels"),
maxPointSize: gl.getUniformLocation(this.program, "uMaxPointSize"),
minPointSize: gl.getUniformLocation(this.program, "uMinPointSize"),
position: gl.getAttribLocation(this.program, "aPosition"),
projection: gl.getUniformLocation(this.program, "uProjection"),
radius: gl.getAttribLocation(this.program, "aRadius"),
view: gl.getUniformLocation(this.program, "uView"),
};
invariant(locations.position >= 0 && locations.radius >= 0 && locations.color >= 0 && locations.alpha >= 0, "WebGL attribute lookup failed");
invariant(locations.projection && locations.view && locations.focalPixels && locations.maxPointSize && locations.minPointSize, "WebGL uniform lookup failed");
return locations;
}
installInteraction() {
let previous = null;
this.canvas.addEventListener("pointerdown", event => {
previous = [event.clientX, event.clientY];
this.canvas.setPointerCapture(event.pointerId);
});
this.canvas.addEventListener("pointermove", event => {
if (!previous || !this.canvas.hasPointerCapture(event.pointerId)) {
return;
}
const next = [event.clientX, event.clientY];
this.camera.orbit(next[0] - previous[0], next[1] - previous[1]);
previous = next;
});
this.canvas.addEventListener("pointerup", event => {
if (this.canvas.hasPointerCapture(event.pointerId)) {
this.canvas.releasePointerCapture(event.pointerId);
}
previous = null;
});
this.canvas.addEventListener("wheel", event => {
event.preventDefault();
this.camera.zoom(event.deltaY);
}, {passive: false});
this.canvas.addEventListener("dblclick", () => {
if (state.scene) {
state.scopeKey=null;this.camera.reset(state.scene);
}
});
this.canvas.addEventListener("keydown", event => {
const orbit = {
ArrowDown: [0, 16],
ArrowLeft: [-16, 0],
ArrowRight: [16, 0],
ArrowUp: [0, -16],
}[event.key];
if (orbit) {
event.preventDefault();
this.camera.orbit(orbit[0], orbit[1]);
} else if (event.key === "+" || event.key === "=") {
event.preventDefault();
this.camera.zoom(-140);
} else if (event.key === "-" || event.key === "_") {
event.preventDefault();
this.camera.zoom(140);
} else if (event.key === "Home" && state.scene) {
event.preventDefault();
state.scopeKey=null;this.camera.reset(state.scene);
}
});
}
resize() {
const ratio = Math.min(window.devicePixelRatio || 1, 2);
const width = Math.max(1, Math.round(this.canvas.clientWidth * ratio));
const height = Math.max(1, Math.round(this.canvas.clientHeight * ratio));
if (this.canvas.width !== width || this.canvas.height !== height) {
this.canvas.width = width;
this.canvas.height = height;
}
return [width, height];
}
bindFloatBuffer(buffer, location, values, components) {
const gl = this.gl;
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, values, gl.DYNAMIC_DRAW);
gl.enableVertexAttribArray(location);
gl.vertexAttribPointer(location, components, gl.FLOAT, false, 0, 0);
}
draw(geometry, scene) {
const gl = this.gl;
const [width, height] = this.resize();
gl.viewport(0, 0, width, height);
gl.clearColor(0, 0, 0, 1);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.enable(gl.DEPTH_TEST);
gl.useProgram(this.program);
this.bindFloatBuffer(this.buffers.alpha, this.locations.alpha, geometry.alpha, 1);
this.bindFloatBuffer(this.buffers.positions, this.locations.position, geometry.positions, 3);
this.bindFloatBuffer(this.buffers.radius, this.locations.radius, geometry.radius, 1);
gl.bindBuffer(gl.ARRAY_BUFFER, this.buffers.colors);
gl.bufferData(gl.ARRAY_BUFFER, geometry.colors, gl.DYNAMIC_DRAW);
gl.enableVertexAttribArray(this.locations.color);
gl.vertexAttribPointer(this.locations.color, 3, gl.UNSIGNED_BYTE, true, 0, 0);
const fov = scene.fov * Math.PI / 180;
const far = Math.max(100, this.camera.distance + this.camera.extent * 40);
gl.uniformMatrix4fv(this.locations.view, false, this.camera.view());
gl.uniformMatrix4fv(this.locations.projection, false, perspective(fov, width / height, 0.005, far));
gl.uniform1f(this.locations.focalPixels, height / (2 * Math.tan(fov / 2)));
gl.uniform1f(this.locations.maxPointSize, this.maxPointSize);
gl.uniform1f(this.locations.minPointSize, scene.min_point_size || 1.25);
for (const pass of pointDrawPasses(geometry)) {
if (pass.blending) {
gl.enable(gl.BLEND);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
} else {
gl.disable(gl.BLEND);
}
gl.depthMask(pass.depthWrite);
gl.drawArrays(gl.POINTS, pass.first, pass.count);
}
gl.depthMask(true);
gl.disable(gl.BLEND);
this.status.textContent = `${geometry.staticCount.toLocaleString()} static · ${geometry.liveCount.toLocaleString()} live`;
}
}
function currentWindowIndex(frame = state.frame) {
return state.assets ? state.assets.frameWindow[frame] : 0;
}
function playbackFrame(time) {
if (!state.scene) {
return 0;
}
return Math.max(0, Math.min(state.scene.frames - 1, Math.floor(time * state.scene.fps + 1e-4)));
}
function seekTimeForFrame(frame, fps) {
// MP4 PTS quantization can round the nominal frame/fps boundary upward.
// Move just inside the requested frame without ever crossing a quarter-frame.
return frame / fps + Math.min(SEEK_BIAS_SECONDS, 0.25 / fps);
}
function updateFrameUi() {
dom.timeline.value = String(state.frame);
dom.frameOutput.textContent = `${state.frame} / ${Math.max(0, state.chunkEnd - 1)}`;
}
function setFrame(frame, seekVideo = true) {
if (!state.scene) {
return;
}
frame = Math.round(Number(frame));
frame = Math.max(state.chunkStart, Math.min(state.chunkEnd - 1, frame));
const changed = frame !== state.frame;
state.frame = frame;
updateFrameUi();
if (seekVideo) {
const target = seekTimeForFrame(frame, state.scene.fps);
// A sub-frame tolerance can leave the paused source image on frame N while
// every 3D panel has already rendered N+1 at an owned-window boundary.
if (
playbackFrame(dom.sourceVideo.currentTime) !== frame
|| Math.abs(dom.sourceVideo.currentTime - target) > 1e-6
) {
dom.sourceVideo.currentTime = target;
}
}
if (changed || seekVideo) {
renderCurrentFrame();
}
}
function setPlaybackUi(playing) {
dom.playIcon.textContent = playing ? "Ⅱ" : "▶";
dom.playLabel.textContent = playing ? "Pause" : "Play";
dom.playButton.setAttribute("aria-label", playing ? "Pause" : "Play");
}
function pause() {
if (!dom.sourceVideo.paused) {
dom.sourceVideo.pause();
}
setPlaybackUi(false);
}
async function play() {
invariant(state.scene, "No scene is loaded");
if (state.frame >= state.chunkEnd - 1) {
setFrame(state.chunkStart);
}
try {
await dom.sourceVideo.play();
setPlaybackUi(true);
} catch (error) {
showError(new Error(`Source video playback failed: ${errorText(error)}`));
}
}
function syncFromVideo(mediaTime = dom.sourceVideo.currentTime) {
if (!state.scene || dom.sourceVideo.seeking) {
return;
}
const frame = playbackFrame(mediaTime);
if (frame >= state.chunkEnd) {
pause();
setFrame(state.chunkEnd - 1);
return;
}
if (frame < state.chunkStart) {
setFrame(state.chunkStart);
return;
}
if (frame !== state.frame) {
setFrame(frame, false);
}
}
function scheduleVideoFrames() {
let callbackId = 0;
const tick = () => {
callbackId = 0;
syncFromVideo();
if (!dom.sourceVideo.paused && !dom.sourceVideo.ended) {
callbackId = setTimeout(tick, 16);
}
};
dom.sourceVideo.addEventListener("play", () => {
if (!callbackId) callbackId = setTimeout(tick, 0);
});
dom.sourceVideo.addEventListener("pause", () => {
clearTimeout(callbackId);
callbackId = 0;
syncFromVideo();
copyInput();
});
dom.sourceVideo.addEventListener("seeked", () => { syncFromVideo(); copyInput(); });
}
function populateChunks(scene) {
dom.chunkSelect.replaceChildren();
const all = document.createElement("option");
all.value = "all";
all.textContent = `All · [0, ${scene.frames})`;
dom.chunkSelect.appendChild(all);
for (const [index, window] of scene.dyn.windows.entries()) {
const option = document.createElement("option");
option.value = String(index);
option.textContent = `C${index} · [${window.start}, ${window.own_end}) · ${window.L} frames`;
dom.chunkSelect.appendChild(option);
}
dom.chunkSelect.value = "all";
state.chunkStart = 0;
state.chunkEnd = scene.frames;
dom.timeline.min = "0";
dom.timeline.max = String(scene.frames - 1);
}
function selectChunk() {
pause();
if (!state.scene) {
return;
}
if (dom.chunkSelect.value === "all") {
state.chunkStart = 0;
state.chunkEnd = state.scene.frames;
} else {
const index = Number(dom.chunkSelect.value);
const window = state.scene.dyn.windows[index];
invariant(window, `Unknown chunk ${dom.chunkSelect.value}`);
state.chunkStart = window.start;
state.chunkEnd = window.own_end;
}
dom.timeline.min = String(state.chunkStart);
dom.timeline.max = String(state.chunkEnd - 1);
setFrame(state.chunkStart);
}
function provenanceSource(provenance) {
return provenance?.source || provenance?.continuous_scene?.manifest?.source || {};
}
function checkpointFields(provenance) {
const checkpoint = provenance?.checkpoint;
const checkpointObject = checkpoint && typeof checkpoint === "object" ? checkpoint : {};
const artifacts = provenance?.assembly_artifacts || {};
const firstArtifact = artifacts.raw || artifacts.stable || {};
return {
architecture: provenance?.checkpoint_architecture || checkpointObject.architecture,
sha256: provenance?.checkpoint_sha256 || checkpointObject.sha256 || provenance?.checkpoint_provenance?.sha256 || provenance?.assembly_manifest?.checkpoint_sha256 || firstArtifact.checkpoint_sha256,
source: provenance?.checkpoint_source || checkpointObject.config_source || provenance?.checkpoint_provenance?.config_source,
uri: (typeof checkpoint === "string" ? checkpoint : checkpointObject.uri) || provenance?.assembly_manifest?.checkpoint_uri || firstArtifact.checkpoint_uri,
};
}
function addSummary(label, value, options = {}) {
const wrapper = document.createElement("div");
if (options.wide) {
wrapper.classList.add("wide");
}
if (options.missing) {
wrapper.classList.add("missing");
}
const term = document.createElement("dt");
term.textContent = label;
const description = document.createElement("dd");
description.textContent = String(value);
wrapper.append(term, description);
dom.provenanceSummary.appendChild(wrapper);
}
function videoReady(scene, generation) {
return new Promise((resolve, reject) => {
const cleanup = () => {
dom.sourceVideo.removeEventListener("loadeddata", loaded);
dom.sourceVideo.removeEventListener("error", failed);
};
const loaded = () => {
cleanup();
if (generation !== state.generation) {
resolve();
return;
}
const expected = (scene.frames - 1) / scene.fps;
invariant(Number.isFinite(dom.sourceVideo.duration) && dom.sourceVideo.duration + 1 / scene.fps >= expected, `${scene.video}: duration ${dom.sourceVideo.duration} does not cover ${scene.frames} frames at ${scene.fps} FPS`);
resolve();
};
const failed = () => {
cleanup();
reject(new Error(`${scene.video}: browser failed to decode the embedded video`));
};
dom.sourceVideo.addEventListener("loadeddata", loaded);
dom.sourceVideo.addEventListener("error", failed);
dom.sourceVideo.src = assetUrl(scene.video);
dom.sourceVideo.load();
});
}
function enableControls(enabled) {
dom.playButton.disabled = !enabled;
dom.chunkSelect.disabled = !enabled;
dom.timeline.disabled = !enabled;
dom.resetCamera.disabled = !enabled;
}
function createRenderers() {
state.camera ??= new OrbitCamera(renderCurrentFrame);
state.renderers = Array.from(document.querySelectorAll(".point-panel")).map(panel => {
if (!panel.pointRenderer) {
panel.pointRenderer = new PointRenderer(panel, state.camera, renderCurrentFrame);
}
return panel.pointRenderer;
});
}
class WireWriter {
constructor(byteLength) {
this.buffer = new ArrayBuffer(byteLength);
this.view = new DataView(this.buffer);
this.offset = 0;
}
i16(...values) {
for (const value of values) {
this.view.setInt16(this.offset, value, true);
this.offset += 2;
}
return this;
}
u16(...values) {
for (const value of values) {
this.view.setUint16(this.offset, value, true);
this.offset += 2;
}
return this;
}
u8(...values) {
for (const value of values) {
this.view.setUint8(this.offset, value);
this.offset += 1;
}
return this;
}
finish() {
invariant(this.offset === this.buffer.byteLength, `wire fixture wrote ${this.offset}/${this.buffer.byteLength} bytes`);
return this.buffer;
}
}
function close(actual, expected, name) {
invariant(Math.abs(actual - expected) <= 1e-6, `${name}: expected ${expected}, got ${actual}`);
}
function runWireSelfTest() {
let checks = 0;
const check = (condition, message) => {
invariant(condition, `wire self-test: ${message}`);
checks += 1;
};
const staticWire = new WireWriter(20)
.i16(1000, 0, 2000)
.u16(1, 5000, 4, 2, 4)
.u8(1, 2, 3, 0)
.finish();
const fixed = decodeStatic(staticWire, 1, 3, "selftest.static");
close(fixed.positions[0], 1, "static x"); checks += 1;
close(fixed.radius[0], 0.5, "static radius"); checks += 1;
check(fixed.birth[0] === 1 && fixed.death[1][0] === 2 && fixed.originWindow[0] === 0, "static fields");
check(!(fixed.birth[0] <= 0 && 0 < fixed.death[0][0]), "birth is inclusive");
check(fixed.birth[0] <= 1 && 1 < fixed.death[0][0], "point visible at birth");
check(!(fixed.birth[0] <= 4 && 4 < fixed.death[0][0]), "death is exclusive");
const dynamicWire = new WireWriter(36)
.i16(1000, 0, 1000, 1000, 0, 1500, 1005, 0, 0, 1000, 0, 0)
.u16(2500, 3750)
.u8(3, 2, 4, 5, 6, 13, 14, 15)
.finish();
const dynamic = decodeTrackWindows(dynamicWire, [{start: 1, own_end: 3, end: 3, n: 2, L: 2}], false, "selftest.dyn")[0];
close(dynamic.positions[6], 2.005, "dynamic delta reconstruction"); checks += 1;
close(dynamic.positions[9], 2, "dynamic second-track delta"); checks += 1;
check(visibilityBit(dynamic, 0, 0) && visibilityBit(dynamic, 0, 1), "visibility frame zero");
check(!visibilityBit(dynamic, 1, 0) && visibilityBit(dynamic, 1, 1), "little-endian visibility bits");
const liveWire = new WireWriter(20)
.i16(1000, 0, 1000, 1000, 0, 0)
.u16(2500)
.u8(1, 1, 10, 11, 12, 1)
.finish();
const live = decodeTrackWindows(liveWire, [{start: 1, own_end: 3, end: 3, n: 1, L: 2}], true, "selftest.live")[0];
check(live.liveStart[0] === 1 && visibilityBit(live, 1, 0), "stable live onset and visibility");
const transformed = new Float32Array(3);
transformAboutCenter(3, 4, 5, [1, 2, 3], 2, transformed, 0);
check(transformed[0] === 5 && transformed[1] === 6 && transformed[2] === 7, "scale about origin-window camera centre");
const blendWindows = [
{end: 8, length: 8, start: 0},
{end: 9, length: 7, start: 2},
];
const firstBlend = crossfadeLayers(blendWindows, 2, 1);
close(firstBlend[0].alpha, 6 / 7, "first shared earlier alpha"); checks += 1;
close(firstBlend[1].alpha, 1 / 7, "first shared later alpha"); checks += 1;
const lastBlend = crossfadeLayers(blendWindows, 7, 1);
close(lastBlend[0].alpha, 1 / 7, "last shared earlier alpha"); checks += 1;
close(lastBlend[1].alpha, 6 / 7, "last shared later alpha"); checks += 1;
check(crossfadeLayers(blendWindows, 8, 1).length === 1, "previous window hidden after overlap");
const alphaGeometry = new GeometryBuilder(1);
alphaGeometry.add(0, 0, 1, 0.01, new Uint8Array([1, 2, 3]), 0, 1 / 7);
close(alphaGeometry.value().alpha[0], 1 / 7, "geometry carries cross-fade alpha"); checks += 1;
const passes = pointDrawPasses({count: 5, fading: true, staticCount: 3});
check(passes.length === 2, "cross-fade renders static and dynamic in separate passes");
check(passes[0].first === 0 && passes[0].count === 3 && passes[0].depthWrite, "static pass writes depth");
check(passes[1].first === 3 && passes[1].count === 2 && passes[1].blending && !passes[1].depthWrite, "fading pass blends without writing depth");
const nonIntegerFps = 30.00834652150149;
const biasedSeek = seekTimeForFrame(41, nonIntegerFps);
check(
biasedSeek > 41 / nonIntegerFps
&& Math.floor(biasedSeek * nonIntegerFps) === 41,
"seek bias stays inside a non-integer-FPS frame",
);
return {checks, ok: true};
}
window.__INFD4RT_VIEWER_SELF_TEST__ = runWireSelfTest;
dom.playButton.addEventListener("click", () => {
if (dom.sourceVideo.paused) {
void play();
} else {
pause();
}
});
dom.resetCamera.addEventListener("click", () => {
if (state.scene) {
state.scopeKey=null;state.camera.reset(state.scene);
}
});
dom.timeline.addEventListener("input", () => {
pause();
setFrame(Number(dom.timeline.value));
});
dom.chunkSelect.addEventListener("change", selectChunk);
dom.sceneSelect.addEventListener("change", () => void loadSelectedScene());
dom.retryButton.addEventListener("click", () => void bootstrap().catch(showError));
dom.sourceVideo.addEventListener("pause", () => setPlaybackUi(false));
dom.sourceVideo.addEventListener("play", () => setPlaybackUi(true));
dom.sourceVideo.addEventListener("seeking", () => {
if (state.scene) {
const frame = playbackFrame(dom.sourceVideo.currentTime);
if (frame >= state.chunkStart && frame < state.chunkEnd) {
state.frame = frame;
updateFrameUi();
renderCurrentFrame();
}
}
});
dom.sourceVideo.addEventListener("ended", pause);
window.addEventListener("unhandledrejection", event => showError(event.reason));
window.addEventListener("error", event => {
if (event.error) {
showError(event.error);
}
});
function queryGeometry(data, gt) {
const positions = gt ? data.q_gt3d : data.q_pred3d;
const valid = gt ? data.q_gtvalid : data.q_predvalid;
const builder = new GeometryBuilder(positions.length);
for (let query = 0; query < positions.length; query += 1) {
if (!data.keep[query] || state.frame < data.q_t_src[query] || !valid[query][state.frame]) continue;
const xyz = positions[query][state.frame];
if (!xyz.every(Number.isFinite)) continue;
const color = gt ? [30, 255, 70] : data.q_colors[query];
builder.add(...xyz, gt ? 0.0035 : 0.0025, color, 0);
}
builder.liveCount = builder.count;
return builder.value();
}
function drawQueryLayer(renderer, geometry, overlay) {
const gl = renderer.gl;
if (overlay) {
gl.disable(gl.DEPTH_TEST);
const pixelRatio = Math.min(window.devicePixelRatio || 1, 2);
const minimum = state.scene.gt_min_point_size || (state.scene.gt_marker_radius_m ? 1.25 : ["pstudio", "adt"].includes(state.currentSample.dataset) ? 6 * pixelRatio : 1.25);
gl.uniform1f(renderer.locations.minPointSize, Math.min(minimum, renderer.maxPointSize));
}
renderer.bindFloatBuffer(renderer.buffers.alpha, renderer.locations.alpha, geometry.alpha, 1);
renderer.bindFloatBuffer(renderer.buffers.positions, renderer.locations.position, geometry.positions, 3);
renderer.bindFloatBuffer(renderer.buffers.radius, renderer.locations.radius, geometry.radius, 1);
gl.bindBuffer(gl.ARRAY_BUFFER, renderer.buffers.colors);
gl.bufferData(gl.ARRAY_BUFFER, geometry.colors, gl.DYNAMIC_DRAW);
gl.vertexAttribPointer(renderer.locations.color, 3, gl.UNSIGNED_BYTE, true, 0, 0);
gl.depthMask(!overlay);
gl.drawArrays(gl.POINTS, 0, geometry.count);
gl.uniform1f(renderer.locations.minPointSize, 1.25);
gl.depthMask(true);
gl.enable(gl.DEPTH_TEST);
}
document.getElementById("show-gt").addEventListener("change", renderCurrentFrame);
window.__TOOLBOX_REVIEW__ = {setFrame, renderCurrentFrame, state};
async function readPackedJson(name) {
const bytes=assetBytes(name);
let value;
if(bytes[0]===0x1f&&bytes[1]===0x8b){
const stream=new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip"));
value=await new Response(stream).json();
}else value=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes));
return value.position_codec?await decodeTrackBlob(value):value;
}
function requestedScene() {
return new URLSearchParams(location.hash.slice(1)).get("scene")
|| new URLSearchParams(location.search).get("scene");
}
window.addEventListener("hashchange", () => {
const requested = requestedScene();
if (state.collection?.some(sample => sample.id === requested) && dom.sceneSelect.value !== requested) {
fillScenes(state.collection.find(sample => sample.id === requested).dataset);
dom.sceneSelect.value = requested;
void loadSelectedScene();
}
});
function validateNativeScene(scene) {
const counts = scene.available_view_counts || [1,2,3,4,5,6,7,8,9,10];
invariant(Number.isInteger(scene.frames) && scene.frames > 0 && scene.states.length > 0, "Expected nonempty matched predictions");
invariant(scene.query_times.length === scene.query_count, "Query timeline length mismatch");
invariant(scene.gt.positions.length === scene.query_count, "Ground-truth query count mismatch");
const pairs = new Set();
const modes = new Set();
scene.states.forEach(entry => {
const camera = entry.camera || "on";
const model = entry.model || "default";
const pair = model + ":" + camera + ":" + entry.views;
invariant(["on","off"].includes(camera) && counts.includes(entry.views) && !pairs.has(pair), "Invalid or duplicate prediction state");
pairs.add(pair);modes.add(model+":"+camera);
invariant(entry.positions.length === scene.query_count, "Prediction query count mismatch");
entry.positions.forEach(points => invariant(points.length === scene.frames, "Prediction frame count mismatch"));
});
modes.forEach(mode => counts.forEach(views => invariant(pairs.has(mode+":"+views), "Missing matched prediction state")));
}
function chosenLayers() {
const primary = {views:Number(document.getElementById("primary-view").value),camera:document.getElementById("primary-camera").value,model:document.getElementById("primary-model").value};
const comparison = {views:Number(document.getElementById("comparison-view").value),camera:document.getElementById("comparison-camera").value,model:document.getElementById("comparison-model").value};
return comparison.views && (comparison.views !== primary.views || comparison.camera !== primary.camera || comparison.model !== primary.model)
? [primary,comparison] : [primary];
}
function predictionState(layer) {
const result = state.scene.states.find(value => value.views === layer.views && (value.camera || "on") === layer.camera && (value.model || "default") === layer.model);
invariant(result, "The selected camera mode and view count are unavailable");
const score=currentScope().scores[layer.model+'_'+layer.camera];
return {...result,aj:score.aj,apd:score.apd,mean_error_cm:score.epe};
}
function layerLabel(layer) {
const model = state.scene.model_labels?.[layer.model];
return (model ? model + " · " : "") + "camera " + layer.camera.toUpperCase() + " · " + layer.views + "v";
}
function configurePredictionSelectors(scene) {
const counts = scene.available_view_counts || [1,2,3,4,5,6,7,8,9,10];
const modes = [...new Set(scene.states.map(value => value.camera || "on"))];
const models = [...new Set(scene.states.map(value => value.model || "default"))];
const paired=document.getElementById("paired-camera");
paired.parentElement.hidden=!scene.match_teacher_inputs;
document.getElementById("primary-camera").parentElement.hidden=!!scene.match_teacher_inputs;
document.getElementById("comparison-camera").parentElement.hidden=!!scene.match_teacher_inputs;
for(const option of paired.options)option.disabled=!modes.includes(option.value);
for (const id of ["primary-model","comparison-model"]) {
const select=document.getElementById(id);select.replaceChildren();
models.forEach(model=>{const option=document.createElement("option");option.value=model;option.textContent=scene.model_labels?.[model]||"SCALE4D";select.appendChild(option);});
select.parentElement.hidden=models.length===1;
}
for (const id of ["primary-view","comparison-view"]) {
const select = document.getElementById(id);
for (const option of select.options) option.disabled = Number(option.value) !== 0 && !counts.includes(Number(option.value));
if (select.selectedOptions[0]?.disabled) select.value = String(counts[0]);
}
for (const id of ["primary-camera","comparison-camera"]) {
const select = document.getElementById(id);
for (const option of select.options) option.disabled = !modes.includes(option.value);
if (!modes.includes(select.value)) select.value = modes[0];
}
if (scene.default_comparison) {
const value = scene.default_comparison;
document.getElementById("primary-view").value = String(value.views);
document.getElementById("comparison-view").value = String(value.views);
document.getElementById("primary-camera").value = value.primary_camera;
document.getElementById("comparison-camera").value = value.comparison_camera;
document.getElementById("primary-model").value = value.primary_model || models[0];
document.getElementById("comparison-model").value = value.comparison_model || models[0];
if(scene.match_teacher_inputs){
paired.value=modes.includes(state.pairedCamera)?state.pairedCamera:value.primary_camera;
document.getElementById("primary-camera").value=paired.value;
document.getElementById("comparison-camera").value=paired.value;
}
}
document.getElementById("dense-context").disabled = !scene.states.some(value => value.dense);
if (scene.default_display) {
document.getElementById("dense-context").checked = scene.default_display.context;
document.getElementById("history-select").value = String(scene.default_display.history);
}
document.getElementById("gt-visible-only").checked = !!scene.default_display?.visible_gt;
document.getElementById("query-density").value = String(scene.default_display?.query_budget || 0);
}
function chosenViews() {
return chosenLayers().map(layer => layer.views);
}
function displayedQueryIds() {
const ids=currentScope().ids;
const budget=Number(document.getElementById("query-density").value);
const count=budget>0?Math.min(budget,ids.length):ids.length;
return Array.from({length:count},(_,i)=>ids[Math.floor(i*ids.length/count)]);
}
function frameGeometry(layer, gt=false, history=0, index=0) {
const sample = state.scene;
const prediction = gt ? sample.gt : predictionState(layer);
const positions = prediction.positions;
const valid = prediction.valid;
const dense = !gt && document.getElementById("dense-context").checked ? prediction.dense : null;
const builder = new GeometryBuilder(sample.query_count*(history+1)+(dense?dense.positions.length:0));
const selected = chosenViews();
const rgb = document.getElementById("rgb-colors").checked && !gt && selected.length === 1;
const shade = gt ? [30,255,70] : index === 0 ? [65,197,255] : [255,156,93];
for(let frame=Math.max(0,state.frame-history); frame<=state.frame; frame++) {
for(const query of displayedQueryIds()) {
if(frame<sample.query_times[query] || !valid[query][frame]) continue;
if (!gt && document.getElementById("gt-visible-only").checked && !sample.gt.valid[query][frame]) continue;
const xyz=positions[query][frame];
if(!xyz.every(Number.isFinite)) continue;
const alpha=frame===state.frame ? 1 : .18+.5*(frame-(state.frame-history))/Math.max(history,1);
builder.add(...xyz,gt ? (sample.gt_marker_radius_m || .004) : (sample.point_radius_m || .003),rgb?sample.colors[query]:shade,0,alpha);
}
}
if(dense) {
for(let query=0;query<dense.positions.length;query++) {
if(!dense.valid[query][state.frame])continue;
const xyz=dense.positions[query][state.frame];
builder.add(...xyz,.009,rgb?dense.colors[query]:shade,0,.75);
}
}
builder.liveCount=builder.count;
builder.fading=history>0;
return builder.value();
}
function combineGeometry(layers) {
const count=layers.reduce((n,layer)=>n+layer.count,0);
const builder=new GeometryBuilder(count);
for(const layer of layers) {
for(let point=0;point<layer.count;point++) {
const offset=point*3;
builder.add(...layer.positions.subarray(offset,offset+3),layer.radius[point],layer.colors,offset,layer.alpha[point]);
}
}
builder.liveCount=count;builder.fading=true;return builder.value();
}
function renderOverlayFrame() {
if(!state.scene || !state.renderers.length) return;
const selected=chosenLayers(),views=selected.map(layer=>layer.views),history=Number(document.getElementById("history-select").value);
const showGt=document.getElementById("show-gt").checked;
const layers=selected.map((layer,index)=>frameGeometry(layer,false,history,index));
const renderer=state.renderers[0];
renderer.draw(combineGeometry(layers),state.scene);
const gt=frameGeometry(0,true,0);
if(showGt)drawQueryLayer(renderer,gt,true);
renderer.gl.flush();
const primary=predictionState(selected[0]);
const comparison=selected.length>1?predictionState(selected[1]):null;
document.getElementById("model-title").textContent="SCALE4D · "+selected.map(layerLabel).join(" vs ");
renderer.status.textContent=selected.map((layer,i)=>layerLabel(layer)+": "+layers[i].count+" points").join(" · ")+" · "+(showGt?gt.count:0)+" GT";
renderer.scale.textContent=(state.scene.position_source==="xyz"?"Native metric XYZ":"Native UV/depth coordinates")+" · no alignment · "+currentScope().ids.length+" scoped scored queries";
const displayed = displayedQueryIds();
if (displayed.length < state.scene.query_count) renderer.scale.textContent += " · "+displayed.length+" fixed queries displayed";
if (document.getElementById("gt-visible-only").checked) renderer.scale.textContent += " · displaying GT-visible queries";
document.getElementById("selected-example").textContent=datasetNames[state.scene.dataset]+" · "+state.scene.label+
" · cyan "+layerLabel(selected[0])+" AJ "+primary.aj.toFixed(2)+"% · scoped error "+primary.mean_error_cm.toFixed(2)+" cm"+
(comparison?" · orange "+layerLabel(selected[1])+" AJ "+comparison.aj.toFixed(2)+"% · scoped error "+comparison.mean_error_cm.toFixed(2)+" cm":"")+
" · "+(selected.length>1&&selected[0].model!==selected[1].model?"separate EMA checkpoints; matched frame and queries":"same checkpoint, frame, and queries");
dom.videoFrame.textContent=String(state.frame);
window.__TOOLBOX_FRAME_REPORT__=[{frame:state.frame,views,cameras:selected.map(layer=>layer.camera),models:selected.map(layer=>layer.model),counts:layers.map(x=>x.count),gt:showGt?gt.count:0,displayed_query_ids:displayed,position_source:state.scene.position_source}];
copyInput();
}
function projectedPoint(xyz,camera) {
const transform=state.scene.relative_cameras[camera][state.frame];
const point=[0,0,0];
for(let row=0;row<3;row++)point[row]=transform[row][3]+transform[row][0]*xyz[0]+transform[row][1]*xyz[1]+transform[row][2]*xyz[2];
if(!point.every(Number.isFinite)||point[2]<=0)return null;
const k=state.scene.intrinsics[camera][state.frame];
const homogeneous=k.map(row=>row[0]*point[0]+row[1]*point[1]+row[2]*point[2]);
return [homogeneous[0]/homogeneous[2]/state.scene.image_width,homogeneous[1]/homogeneous[2]/state.scene.image_height];
}
function copyInput() {
const video=dom.sourceVideo;if(!state.scene)return;
if(video.readyState<2||video.seeking||playbackFrame(video.currentTime)!==state.frame||video.currentSrc!==assetUrl(state.scene.video)){
const canvas=document.getElementById("single-input");
canvas.getContext("2d").clearRect(0,0,canvas.width,canvas.height);
dom.inputStatus.textContent="Loading RGB frame "+state.frame;
window.__TOOLBOX_RGB_FRAME__=null;
return;
}
const camera=Number(document.getElementById("display-camera").value),grid=state.scene.video_grid;
const canvas=document.getElementById("single-input"),stage=canvas.parentElement.getBoundingClientRect(),ratio=Math.min(window.devicePixelRatio||1,2);
canvas.width=Math.max(1,Math.round(stage.width*ratio));canvas.height=Math.max(1,Math.round(stage.height*ratio));
const context=canvas.getContext("2d"),scale=Math.min(canvas.width/grid.cell_width,canvas.height/grid.cell_height);
const width=grid.cell_width*scale,height=grid.cell_height*scale,x=(canvas.width-width)/2,y=(canvas.height-height)/2;
context.fillStyle="#000";context.fillRect(0,0,canvas.width,canvas.height);
context.drawImage(video,(camera%grid.columns)*grid.cell_width,Math.floor(camera/grid.columns)*grid.cell_height,grid.cell_width,grid.cell_height,x,y,width,height);
const selected=chosenLayers();
const arrays=selected.map((layer,index)=>{const prediction=predictionState(layer);return {positions:prediction.positions,valid:prediction.valid,color:index?"#ff9c5d":"#41c5ff"};});
if(document.getElementById("show-gt").checked)arrays.push({positions:state.scene.gt.positions,valid:state.scene.gt.valid,color:"#1eff46",radius:state.scene.gt_pixel_radius||2.0});
for(const layer of arrays) {
context.fillStyle=layer.color;
for(const query of displayedQueryIds()) {
if(state.frame<state.scene.query_times[query]||!layer.valid[query][state.frame])continue;
if (document.getElementById("gt-visible-only").checked && !state.scene.gt.valid[query][state.frame]) continue;
const uv=projectedPoint(layer.positions[query][state.frame],camera);
if(!uv||uv[0]<0||uv[1]<0||uv[0]>1||uv[1]>1)continue;
context.beginPath();context.arc(x+uv[0]*width,y+uv[1]*height,(layer.radius||2.0)*ratio,0,Math.PI*2);context.fill();
}
}
dom.inputStatus.textContent="Camera "+state.scene.camera_ids[camera]+" · display only";
window.__TOOLBOX_RGB_FRAME__={scene:state.scene.id,frame:state.frame,video_frame:playbackFrame(video.currentTime)};
}
function waitForRgbFrame(generation) {
return new Promise((resolve,reject)=>{
let timeout;
const cleanup=()=>{
clearTimeout(timeout);
for(const event of ["seeked","loadeddata","error"])dom.sourceVideo.removeEventListener(event,check);
};
const check=()=>{
if(generation!==state.generation){cleanup();resolve();return;}
if(dom.sourceVideo.error){cleanup();reject(new Error("Could not decode the selected RGB frame"));return;}
copyInput();
if(window.__TOOLBOX_RGB_FRAME__){cleanup();resolve();}
};
for(const event of ["seeked","loadeddata","error"])dom.sourceVideo.addEventListener(event,check);
timeout=setTimeout(()=>{cleanup();reject(new Error("Selected RGB frame did not become ready"));},15000);
check();
});
}
async function loadSelectedScene() {
const selected=state.collection.find(sample=>sample.id===dom.sceneSelect.value);
invariant(selected,"Unknown candidate");
const generation=++state.generation;
pause();enableControls(false);hideError();window.__TOOLBOX_READY__=false;
try {
setLoading("Loading candidate","Reading the matched SCALE4D predictions",.1);
const scene=await readPackedJson(selected.data);
if(generation!==state.generation)return;
validateNativeScene(scene);
state.scene=scene;state.currentSample=selected;
configurePredictionSelectors(scene);
state.assets={frameWindow:new Int16Array(scene.frames)};
state.camera.reset(scene,false);
state.frame=0;populateChunks(scene);
const camera=document.getElementById("display-camera");camera.replaceChildren();
scene.camera_ids.forEach((id,index)=>{const option=document.createElement("option");option.value=String(index);option.textContent="Camera "+id+(index===0?" (target)":"");camera.appendChild(option);});
camera.value=String(scene.default_display_camera ?? 1);
updateProvenance(scene);
await videoReady(scene,generation);
if(generation!==state.generation)return;
setFrame(scene.default_frame||30);
await waitForRgbFrame(generation);
if(generation!==state.generation)return;
enableControls(true);finishLoading();window.__TOOLBOX_READY__=true;
}catch(error){if(generation===state.generation)showError(error);}
}
function updateProvenance(scene) {
dom.provenanceSummary.replaceChildren();
addSummary("Model",scene.model_description || "SCALE4D · frozen 140k checkpoint");
addSummary("Input counts",(scene.available_view_counts||[1,2,3,4,5,6,7,8,9,10]).join(", ")+" input views; target camera fixed");
addSummary("Conditioning",scene.comparison_description || (scene.states.some(value=>value.camera==="off")?"ON and OFF use identical images, queries, camera order, and frozen checkpoint. Only camera conditioning changes.":"Camera conditioning ON"));
addSummary("Coordinates",scene.position_source==="xyz"?"Native metric XYZ tracks used by the distillation evaluator; target-camera coordinates":"Exactly the UV-and-predicted-depth lifting used in Figure 11; native metric target-camera coordinates");
addSummary("Geometry",scene.query_count+" complete scored query trajectories in native metric coordinates.");
if(scene.states.some(value=>value.dense))addSummary("Context","The additional source-frame-zero pixel-grid predictions provide scene context. Scores above use the original benchmark queries.");
if(scene.default_display?.visible_gt)addSummary("Display filter","GT-visible queries shows both teachers on queries with visible ground truth at each frame. Turn it off to display all predictions. Scores use the complete scored clip.");
addSummary("Query density","Lower densities use fixed, evenly spaced query IDs shared by both teachers and GT. Sampling uses query order, independent of prediction errors. All queries remain available; scores use the full clip.");
addSummary("Display camera","The reference reference camera can be outside the chosen model input subset. It is used only to display projections.");
addSummary("Selection",scene.selection);
addSummary("Reference","Adapted from the supplied Pixelcloud viewer; its older checkpoint data is replaced.");
dom.windowDetails.textContent=JSON.stringify(scene.benchmark_scores,null,2);
dom.reportDetails.textContent=JSON.stringify(scene.states.map(x=>({input_views:x.views,camera_conditioning:x.camera||"on",aj_percent:x.aj,apd_percent:x.apd,mean_error_cm:x.mean_error_cm})),null,2);
dom.provenanceDetails.textContent=JSON.stringify(scene.checkpoint_provenance||{model:"SCALE4D",checkpoint_iteration:scene.checkpoint_iteration||140000,frames:scene.frames,position_source:scene.position_source,query_count:scene.query_count},null,2);
}
async function bootstrap() {
try {
enableControls(false);hideError();
const result=runWireSelfTest();window.__VIEWER_SELF_TEST_RESULT__=result;
dom.selfTestStatus.textContent="renderer self-test passed · "+result.checks+" checks";dom.selfTestStatus.classList.add("passed");
createRenderers();
state.collection=await readPackedJson("scenes.json");
invariant(state.collection.length>0,"Expected sample scenes");
const datasets=[...new Set(state.collection.map(item=>item.dataset))];
const datasetSelect=document.getElementById("dataset-select");datasetSelect.replaceChildren();
datasets.forEach(dataset=>{const option=document.createElement("option");option.value=dataset;datasetNames[dataset]=state.collection.find(item=>item.dataset===dataset).dataset_label||datasetNames[dataset]||dataset;option.textContent=datasetNames[dataset];datasetSelect.appendChild(option);});
fillScenes(datasets[0]);
const requested=requestedScene();const chosen=state.collection.find(x=>x.id===requested);
if(chosen)fillScenes(chosen.dataset);
dom.sceneSelect.value=chosen?.id||state.collection[0].id;
await loadSelectedScene();
}catch(error){showError(error);}
}
["primary-view","comparison-view","primary-model","comparison-model","primary-camera","comparison-camera","display-camera","rgb-colors","history-select","dense-context","gt-visible-only","query-density"].forEach(id=>document.getElementById(id).addEventListener("change",renderCurrentFrame));
document.getElementById("paired-camera").addEventListener("change",event=>{
state.pairedCamera=event.target.value;
document.getElementById("primary-camera").value=event.target.value;
document.getElementById("comparison-camera").value=event.target.value;
renderCurrentFrame();
});
window.__TOOLBOX_REVIEW__={setFrame,renderCurrentFrame,state};
scheduleVideoFrames();
bootstrap().catch(showError);
function currentScope() {
const key = document.getElementById('point-scope').value || 'object';
return {key, ...state.scene.scopes[key]};
}
function metricScopeLabel() {
return currentScope().key === 'all' ? 'full-clip error' : currentScope().label.toLowerCase() + ' error';
}
function updateScopeCamera() {
const scope = currentScope();
const key = state.scene.id + ':' + scope.key;
if (state.scopeKey !== key) {
state.camera.reset({...state.scene, target: scope.view.targets[state.frame], extent: scope.view.extent}, false);
state.scopeKey = key;
}
state.camera.target = scope.view.targets[state.frame].map(Number);
}
function renderCurrentFrame() {
if (!state.scene || !state.renderers.length) return;
const four = document.getElementById('comparison-layout').value === 'four';
document.body.classList.toggle('four-way', four);
for (const id of ['paired-camera','primary-model','comparison-model','primary-view','comparison-view']) {
document.getElementById(id).parentElement.hidden = four;
}
const rgbLabel=document.getElementById('rgb-colors').closest('label');
if(rgbLabel) rgbLabel.hidden=four;
updateScopeCamera();
renderOverlayFrame();
if (!four) return;
document.getElementById('rgb-colors').checked=false;
const history = Number(document.getElementById('history-select').value);
const gt = frameGeometry(0, true, 0);
const showGt = document.getElementById('show-gt').checked;
const scope = currentScope();
const pairs = [
{model:'b2_ema',camera:'off',views:3},
{model:'b3_ema',camera:'off',views:3},
{model:'b2_ema',camera:'on',views:3},
{model:'b3_ema',camera:'on',views:3},
];
const reports = [];
for (let index = 0; index < pairs.length; index++) {
const layer = pairs[index], renderer = state.renderers[index];
const geometry = frameGeometry(layer, false, history, layer.model === 'b3_ema' ? 0 : 1);
renderer.draw(geometry, state.scene);
if (showGt) drawQueryLayer(renderer, gt, true);
renderer.gl.flush();
const score = predictionState(layer);
renderer.panel.querySelector('h2').textContent = layer.camera.toUpperCase() + ' · ' + (layer.model === 'b3_ema' ? 'B3' : 'B2') + ' · ' + score.mean_error_cm.toFixed(2) + ' cm';
renderer.status.textContent = '';
renderer.scale.textContent = scope.label + ' · shared GT and view · ' + geometry.count + ' predictions / ' + gt.count + ' GT';
reports.push({frame:state.frame,model:layer.model,camera:layer.camera,views:3,query_ids:displayedQueryIds(),prediction_count:geometry.count,gt_count:gt.count,mean_error_cm:score.mean_error_cm});
}
document.getElementById('selected-example').textContent = state.scene.label + ' · ' + scope.label + ' · '+scope.ids.length+' scoped scored queries · saved EMA 65k · 3 views · cyan B3 · orange B2 · green GT · all four panels share the same frame, GT queries and view';
window.__TOOLBOX_FRAME_REPORT__ = reports;
window.__QUAD_REVIEW__ = {scope:scope.key,scored_queries:scope.ids.length,displayed_queries:displayedQueryIds().length,shared_target:state.camera.target.slice(),reports};
}
document.getElementById('comparison-layout').addEventListener('change', renderCurrentFrame);
document.getElementById('point-scope').addEventListener('change', () => {
state.scopeKey = null;
renderCurrentFrame();
});
async function decodeTrackBlob(scene) {
const codec=scene.position_codec;
if(!codec)return scene;
if(codec.version!==1||codec.scale!==10000)throw new Error('Unsupported coordinate codec');
const stream=new Blob([assetBytes(codec.asset)]).stream().pipeThrough(new DecompressionStream('gzip'));
const bytes=new Uint8Array(await new Response(stream).arrayBuffer());
const integers=[];
let cursor=0;
function signed(){
let value=0,shift=0,byte;
do{
if(cursor>=bytes.length||shift>35)throw new Error('Malformed coordinate stream');
byte=bytes[cursor++];value+=(byte&127)*2**shift;shift+=7;
}while(byte&128);
return value%2?-(value+1)/2:value/2;
}
for(let layer=0;layer<codec.layers.length;layer++){
const description=codec.layers[layer];
const result=description.state<0?scene.gt:scene.states[description.state];
const base=description.base<0?null:integers[description.base];
const quantized=new Int32Array(scene.query_count*scene.frames*3);
const positions=[];
let hash=2166136261;
for(let query=0;query<scene.query_count;query++){
const previous=[0,0,0],track=[];
for(let frame=0;frame<scene.frames;frame++){
const xyz=[];
for(let axis=0;axis<3;axis++){
const index=(query*scene.frames+frame)*3+axis;
previous[axis]+=signed();
const value=previous[axis]+(base?base[index]:0);
quantized[index]=value;xyz.push(value/codec.scale);
hash=Math.imul(hash^(value|0),16777619)>>>0;
}
track.push(xyz);
}
positions.push(track);
}
if(hash.toString(16).padStart(8,'0')!==codec.checksums[layer])throw new Error('Coordinate checksum mismatch');
result.positions=positions;integers.push(quantized);
}
if(cursor!==bytes.length)throw new Error('Unexpected coordinate bytes');
scene.coordinate_codec_verified=true;
return scene;
}
|