simview 6.3.0__tar.gz → 6.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. {simview-6.3.0/simview.egg-info → simview-6.4.0}/PKG-INFO +1 -1
  2. {simview-6.3.0 → simview-6.4.0}/pyproject.toml +1 -1
  3. {simview-6.3.0 → simview-6.4.0}/simview/__main__.py +8 -2
  4. {simview-6.3.0 → simview-6.4.0}/simview/model.py +15 -1
  5. simview-6.4.0/simview/preload.py +69 -0
  6. {simview-6.3.0 → simview-6.4.0}/simview/scene.py +10 -2
  7. {simview-6.3.0 → simview-6.4.0}/simview/server.py +14 -3
  8. {simview-6.3.0 → simview-6.4.0}/simview/static/js/SimView.js +64 -45
  9. {simview-6.3.0 → simview-6.4.0}/simview/static/js/components/BatchManager.js +9 -1
  10. {simview-6.3.0 → simview-6.4.0}/simview/static/js/components/InteractionController.js +38 -1
  11. {simview-6.3.0 → simview-6.4.0}/simview/static/js/components/Scene.js +55 -1
  12. {simview-6.3.0 → simview-6.4.0}/simview/static/js/components/StateStore.js +23 -0
  13. {simview-6.3.0 → simview-6.4.0}/simview/static/js/config.js +2 -1
  14. {simview-6.3.0 → simview-6.4.0}/simview/static/js/objects/Body.js +33 -8
  15. {simview-6.3.0 → simview-6.4.0}/simview/static/js/objects/Terrain.js +46 -17
  16. {simview-6.3.0 → simview-6.4.0}/simview/static/js/ui/BodyStateWindow.js +3 -0
  17. {simview-6.3.0 → simview-6.4.0}/simview/static/js/ui/Controls.js +78 -11
  18. {simview-6.3.0 → simview-6.4.0}/simview/static/js/ui/Legend.js +4 -2
  19. {simview-6.3.0 → simview-6.4.0}/simview/templates/index.html +11 -0
  20. {simview-6.3.0 → simview-6.4.0/simview.egg-info}/PKG-INFO +1 -1
  21. {simview-6.3.0 → simview-6.4.0}/simview.egg-info/SOURCES.txt +2 -0
  22. {simview-6.3.0 → simview-6.4.0}/tests/test_pointcloud_features.py +15 -0
  23. simview-6.4.0/tests/test_preload.py +25 -0
  24. {simview-6.3.0 → simview-6.4.0}/LICENSE +0 -0
  25. {simview-6.3.0 → simview-6.4.0}/MANIFEST.in +0 -0
  26. {simview-6.3.0 → simview-6.4.0}/README.md +0 -0
  27. {simview-6.3.0 → simview-6.4.0}/setup.cfg +0 -0
  28. {simview-6.3.0 → simview-6.4.0}/simview/__init__.py +0 -0
  29. {simview-6.3.0 → simview-6.4.0}/simview/columnar.py +0 -0
  30. {simview-6.3.0 → simview-6.4.0}/simview/diff.py +0 -0
  31. {simview-6.3.0 → simview-6.4.0}/simview/info.py +0 -0
  32. {simview-6.3.0 → simview-6.4.0}/simview/launcher.py +0 -0
  33. {simview-6.3.0 → simview-6.4.0}/simview/live.py +0 -0
  34. {simview-6.3.0 → simview-6.4.0}/simview/merge.py +0 -0
  35. {simview-6.3.0 → simview-6.4.0}/simview/py.typed +0 -0
  36. {simview-6.3.0 → simview-6.4.0}/simview/remote.py +0 -0
  37. {simview-6.3.0 → simview-6.4.0}/simview/render.py +0 -0
  38. {simview-6.3.0 → simview-6.4.0}/simview/state.py +0 -0
  39. {simview-6.3.0 → simview-6.4.0}/simview/static/css/controls.css +0 -0
  40. {simview-6.3.0 → simview-6.4.0}/simview/static/js/components/AnimationController.js +0 -0
  41. {simview-6.3.0 → simview-6.4.0}/simview/static/js/components/WindowedField.js +0 -0
  42. {simview-6.3.0 → simview-6.4.0}/simview/static/js/main.js +0 -0
  43. {simview-6.3.0 → simview-6.4.0}/simview/static/js/objects/Polyline.js +0 -0
  44. {simview-6.3.0 → simview-6.4.0}/simview/static/js/objects/StaticObject.js +0 -0
  45. {simview-6.3.0 → simview-6.4.0}/simview/static/js/objects/colormap.js +0 -0
  46. {simview-6.3.0 → simview-6.4.0}/simview/static/js/objects/similarity.js +0 -0
  47. {simview-6.3.0 → simview-6.4.0}/simview/static/js/objects/utils.js +0 -0
  48. {simview-6.3.0 → simview-6.4.0}/simview/static/js/ui/AnalysisPanel.js +0 -0
  49. {simview-6.3.0 → simview-6.4.0}/simview/static/js/ui/BatchLegend.js +0 -0
  50. {simview-6.3.0 → simview-6.4.0}/simview/static/js/ui/ErrorMetrics.js +0 -0
  51. {simview-6.3.0 → simview-6.4.0}/simview/static/js/ui/PlaybackControls.js +0 -0
  52. {simview-6.3.0 → simview-6.4.0}/simview/static/js/ui/ScalarPlotter.js +0 -0
  53. {simview-6.3.0 → simview-6.4.0}/simview/static/js/ui/TerrainProfile.js +0 -0
  54. {simview-6.3.0 → simview-6.4.0}/simview/static/js/ui/chartControls.js +0 -0
  55. {simview-6.3.0 → simview-6.4.0}/simview/static/js/utils/batchPresets.js +0 -0
  56. {simview-6.3.0 → simview-6.4.0}/simview/static/js/utils/batchVisibility.js +0 -0
  57. {simview-6.3.0 → simview-6.4.0}/simview/static/js/utils/blobCodec.js +0 -0
  58. {simview-6.3.0 → simview-6.4.0}/simview/static/js/utils/blobWindow.js +0 -0
  59. {simview-6.3.0 → simview-6.4.0}/simview/static/js/utils/bodyTransforms.js +0 -0
  60. {simview-6.3.0 → simview-6.4.0}/simview/static/js/utils/cameraRange.js +0 -0
  61. {simview-6.3.0 → simview-6.4.0}/simview/static/js/utils/csv.js +0 -0
  62. {simview-6.3.0 → simview-6.4.0}/simview/static/js/utils/episodes.js +0 -0
  63. {simview-6.3.0 → simview-6.4.0}/simview/static/js/utils/errorMath.js +0 -0
  64. {simview-6.3.0 → simview-6.4.0}/simview/static/js/utils/html.js +0 -0
  65. {simview-6.3.0 → simview-6.4.0}/simview/static/js/utils/interpolate.js +0 -0
  66. {simview-6.3.0 → simview-6.4.0}/simview/static/js/utils/keyboard.js +0 -0
  67. {simview-6.3.0 → simview-6.4.0}/simview/static/js/utils/liveFollow.js +0 -0
  68. {simview-6.3.0 → simview-6.4.0}/simview/static/js/utils/scalarSeries.js +0 -0
  69. {simview-6.3.0 → simview-6.4.0}/simview/static/js/utils/terrainSample.js +0 -0
  70. {simview-6.3.0 → simview-6.4.0}/simview/static/js/utils/uplot.js +0 -0
  71. {simview-6.3.0 → simview-6.4.0}/simview/static/js/utils/viewState.js +0 -0
  72. {simview-6.3.0 → simview-6.4.0}/simview/static/js/utils/viewerDefaults.js +0 -0
  73. {simview-6.3.0 → simview-6.4.0}/simview/static/js/utils/visibleRanges.js +0 -0
  74. {simview-6.3.0 → simview-6.4.0}/simview/static/js/vendor/js-colormaps.js +0 -0
  75. {simview-6.3.0 → simview-6.4.0}/simview/static/lib/three-0.174.0/addons/controls/OrbitControls.js +0 -0
  76. {simview-6.3.0 → simview-6.4.0}/simview/static/lib/three-0.174.0/addons/libs/lil-gui.module.min.js +0 -0
  77. {simview-6.3.0 → simview-6.4.0}/simview/static/lib/three-0.174.0/three.core.js +0 -0
  78. {simview-6.3.0 → simview-6.4.0}/simview/static/lib/three-0.174.0/three.module.js +0 -0
  79. {simview-6.3.0 → simview-6.4.0}/simview/static/lib/uPlot-1.6.32/uPlot.esm.js +0 -0
  80. {simview-6.3.0 → simview-6.4.0}/simview/static/lib/uPlot-1.6.32/uPlot.min.css +0 -0
  81. {simview-6.3.0 → simview-6.4.0}/simview/static/textures/contacts/red-cross0.png +0 -0
  82. {simview-6.3.0 → simview-6.4.0}/simview/static/textures/points/ball1.png +0 -0
  83. {simview-6.3.0 → simview-6.4.0}/simview/terrain.py +0 -0
  84. {simview-6.3.0 → simview-6.4.0}/simview/utils.py +0 -0
  85. {simview-6.3.0 → simview-6.4.0}/simview/view.py +0 -0
  86. {simview-6.3.0 → simview-6.4.0}/simview.egg-info/dependency_links.txt +0 -0
  87. {simview-6.3.0 → simview-6.4.0}/simview.egg-info/entry_points.txt +0 -0
  88. {simview-6.3.0 → simview-6.4.0}/simview.egg-info/requires.txt +0 -0
  89. {simview-6.3.0 → simview-6.4.0}/simview.egg-info/top_level.txt +0 -0
  90. {simview-6.3.0 → simview-6.4.0}/tests/test_batch_selection.py +0 -0
  91. {simview-6.3.0 → simview-6.4.0}/tests/test_cli.py +0 -0
  92. {simview-6.3.0 → simview-6.4.0}/tests/test_columnar_ondisk.py +0 -0
  93. {simview-6.3.0 → simview-6.4.0}/tests/test_columnar_states.py +0 -0
  94. {simview-6.3.0 → simview-6.4.0}/tests/test_contacts.py +0 -0
  95. {simview-6.3.0 → simview-6.4.0}/tests/test_diff.py +0 -0
  96. {simview-6.3.0 → simview-6.4.0}/tests/test_embed_defaults.py +0 -0
  97. {simview-6.3.0 → simview-6.4.0}/tests/test_episodes.py +0 -0
  98. {simview-6.3.0 → simview-6.4.0}/tests/test_info.py +0 -0
  99. {simview-6.3.0 → simview-6.4.0}/tests/test_launcher.py +0 -0
  100. {simview-6.3.0 → simview-6.4.0}/tests/test_live.py +0 -0
  101. {simview-6.3.0 → simview-6.4.0}/tests/test_merge.py +0 -0
  102. {simview-6.3.0 → simview-6.4.0}/tests/test_remote.py +0 -0
  103. {simview-6.3.0 → simview-6.4.0}/tests/test_roundtrip.py +0 -0
  104. {simview-6.3.0 → simview-6.4.0}/tests/test_scene.py +0 -0
  105. {simview-6.3.0 → simview-6.4.0}/tests/test_server.py +0 -0
  106. {simview-6.3.0 → simview-6.4.0}/tests/test_show.py +0 -0
  107. {simview-6.3.0 → simview-6.4.0}/tests/test_terrain.py +0 -0
  108. {simview-6.3.0 → simview-6.4.0}/tests/test_terrain_query.py +0 -0
  109. {simview-6.3.0 → simview-6.4.0}/tests/test_trajectory.py +0 -0
  110. {simview-6.3.0 → simview-6.4.0}/tests/test_utils.py +0 -0
  111. {simview-6.3.0 → simview-6.4.0}/tests/test_view.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: simview
3
- Version: 6.3.0
3
+ Version: 6.4.0
4
4
  Summary: THREE.js-based simulation visualization tool
5
5
  Author-email: Jan Vlk <vlkjan6@fel.cvut.cz>, Ales Kucera <kuceral4@fel.cvut.cz>, David Korcak <david.korcak@gmail.com>
6
6
  License-Expression: BSD-3-Clause
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "simview"
7
- version = "6.3.0"
7
+ version = "6.4.0"
8
8
  readme = "README.md"
9
9
  requires-python = ">=3.12"
10
10
  license = "BSD-3-Clause"
@@ -82,8 +82,14 @@ def export_static_viewer(directory: Path) -> None:
82
82
 
83
83
  package = files("simview")
84
84
  directory.mkdir(parents=True, exist_ok=True)
85
- shutil.copy(str(package / "templates" / "index.html"), directory / "index.html")
86
- shutil.copytree(str(package / "static"), directory / "static", dirs_exist_ok=True)
85
+ from simview.preload import render_index
86
+
87
+ index = package / "templates" / "index.html"
88
+ static = package / "static"
89
+ (directory / "index.html").write_text(
90
+ render_index(str(index), str(package)), encoding="utf-8"
91
+ )
92
+ shutil.copytree(str(static), directory / "static", dirs_exist_ok=True)
87
93
  logger.info("Static viewer written to %s", directory)
88
94
 
89
95
 
@@ -488,6 +488,7 @@ class SimViewBody:
488
488
  points: torch.Tensor,
489
489
  color: torch.Tensor | None = None,
490
490
  embedding: torch.Tensor | None = None,
491
+ color_layers: dict[str, torch.Tensor] | None = None,
491
492
  **kwargs,
492
493
  ) -> "SimViewBody":
493
494
  """Build a point-cloud body from `(N, 3)` `points`.
@@ -497,7 +498,10 @@ class SimViewBody:
497
498
  an optional per-point K-wide feature vector (e.g. a reduced-dim PCA
498
499
  projection of a learned backbone's features) enabling the viewer's
499
500
  click-to-similarity color mode: cosine similarity to a clicked point,
500
- computed entirely in-browser from this data. Both are stored as
501
+ computed entirely in-browser from this data. `color_layers` maps a
502
+ name to another (N, 3) RGB coloring (e.g. a class or session label);
503
+ each becomes an extra choice of the viewer's "Point Color Mode", shown
504
+ by every body that ships a layer of that name. All are stored as
501
505
  ``__b64__`` blobs."""
502
506
  if points.ndim != 2 or points.shape[1] != 3:
503
507
  raise ValueError(
@@ -517,6 +521,16 @@ class SimViewBody:
517
521
  f"embedding must have shape ({N}, K) matching points; got {tuple(embedding.shape)}."
518
522
  )
519
523
  shape_extra["embedding"] = embedding
524
+ if color_layers:
525
+ shape_extra["colorLayers"] = {}
526
+ for layer, rgb in color_layers.items():
527
+ if layer in ("pca", "similarity"):
528
+ raise ValueError(f"color layer name {layer!r} is reserved.")
529
+ if tuple(rgb.shape) != (N, 3):
530
+ raise ValueError(
531
+ f"color layer {layer!r} must have shape ({N}, 3); got {tuple(rgb.shape)}."
532
+ )
533
+ shape_extra["colorLayers"][layer] = _encode_blob(rgb.cpu().numpy())
520
534
  # Per-point `color` lives in the shape, so it can't go through
521
535
  # `create`'s kwargs (where `color` is the body-level tint).
522
536
  body = SimViewBody.create(
@@ -0,0 +1,69 @@
1
+ """`<link rel="modulepreload">` tags for the viewer page.
2
+
3
+ The browser only discovers an ES module's imports after it has fetched and
4
+ parsed the importer, so the ~50-file module graph downloads one dependency
5
+ level at a time. Listing every module in the page head lets them all start at
6
+ once (a ~50 ms round trip each otherwise adds up level by level).
7
+ """
8
+
9
+ import json
10
+ import re
11
+ from functools import cache
12
+ from pathlib import Path
13
+
14
+ # `import ... from "x"`, `export ... from "x"` and side-effect `import "x"`.
15
+ # Dynamic import() is skipped: those modules are lazy on purpose.
16
+ _STATIC_IMPORT = re.compile(
17
+ r"""(?:^|[;\n])\s*(?:import|export)\b[^;'"]*?(?:\bfrom\s*)?["']([^"']+)["']\s*;?""",
18
+ )
19
+ _IMPORTMAP = re.compile(r'<script type="importmap">(.*?)</script>', re.S)
20
+ PLACEHOLDER = "<!-- @modulepreload -->"
21
+
22
+
23
+ def _resolve(
24
+ spec: str, importer: Path, root: Path, imports: dict[str, str]
25
+ ) -> Path | None:
26
+ """Filesystem path `spec` points at, or None for anything outside `root`."""
27
+ if spec.startswith("."):
28
+ target = importer.parent / spec
29
+ else:
30
+ # Bare specifier -> import map; "prefix/" entries map whole directories.
31
+ for key, value in imports.items():
32
+ if spec == key or (key.endswith("/") and spec.startswith(key)):
33
+ target = root / (value + spec[len(key) :])
34
+ break
35
+ else:
36
+ return None
37
+ target = target.resolve()
38
+ return target if target.is_file() and root in target.parents else None
39
+
40
+
41
+ def module_graph(html: str, root: Path, entry: str = "static/js/main.js") -> list[str]:
42
+ """Page-relative URLs (`./static/...`) of every module reachable from `entry`."""
43
+ match = _IMPORTMAP.search(html)
44
+ imports = json.loads(match.group(1))["imports"] if match else {}
45
+ imports = {k: v.removeprefix("./") for k, v in imports.items()}
46
+ root = root.resolve()
47
+ seen: dict[Path, None] = {}
48
+ todo = [(root / entry).resolve()]
49
+ while todo:
50
+ path = todo.pop()
51
+ if path in seen:
52
+ continue
53
+ seen[path] = None
54
+ for spec in _STATIC_IMPORT.findall(path.read_text(encoding="utf-8")):
55
+ dep = _resolve(spec, path, root, imports)
56
+ if dep is not None:
57
+ todo.append(dep)
58
+ return ["./" + p.relative_to(root).as_posix() for p in seen]
59
+
60
+
61
+ @cache
62
+ def render_index(index_path: str, root: str) -> str:
63
+ """index.html with its modulepreload placeholder filled in."""
64
+ html = Path(index_path).read_text(encoding="utf-8")
65
+ links = "\n ".join(
66
+ f'<link rel="modulepreload" href="{url}" />'
67
+ for url in module_graph(html, Path(root))
68
+ )
69
+ return html.replace(PLACEHOLDER, links)
@@ -794,6 +794,7 @@ class SimulationScene:
794
794
  points: torch.Tensor,
795
795
  color: torch.Tensor | None = None,
796
796
  embedding: torch.Tensor | None = None,
797
+ color_layers: dict[str, torch.Tensor] | None = None,
797
798
  **kwargs,
798
799
  ) -> None:
799
800
  """Add a point-cloud body named `body_name` to the model.
@@ -802,11 +803,18 @@ class SimulationScene:
802
803
  `(N, 3)` per-point RGB in [0, 1] for static vertex-colored rendering.
803
804
  `embedding` is an optional `(N, K)` per-point feature vector (e.g. a
804
805
  reduced-dim PCA projection) enabling the viewer's click-to-similarity
805
- color mode. Other `**kwargs` go to `SimViewBody.create`.
806
+ color mode. `color_layers` maps names to extra `(N, 3)` RGB colorings
807
+ selectable as "Point Color Mode" choices. Other `**kwargs` go to
808
+ `SimViewBody.create`.
806
809
  """
807
810
  self.model.add_body(
808
811
  SimViewBody.create_pointcloud(
809
- body_name, points, color=color, embedding=embedding, **kwargs
812
+ body_name,
813
+ points,
814
+ color=color,
815
+ embedding=embedding,
816
+ color_layers=color_layers,
817
+ **kwargs,
810
818
  )
811
819
  )
812
820
 
@@ -21,13 +21,15 @@ import orjson
21
21
  import uvicorn
22
22
  from fastapi import FastAPI, Request, Response, WebSocket, WebSocketDisconnect
23
23
  from fastapi.middleware.cors import CORSMiddleware
24
- from fastapi.responses import FileResponse, JSONResponse
24
+ from fastapi.responses import HTMLResponse, JSONResponse
25
25
  from fastapi.staticfiles import StaticFiles
26
26
  from pydantic import BaseModel
27
27
  from starlette.datastructures import Headers
28
+ from starlette.middleware.gzip import GZipMiddleware
28
29
  from starlette.types import Scope
29
30
 
30
31
  from simview.columnar import columnarize_states, is_columnar, rewrite_blobs
32
+ from simview.preload import render_index
31
33
  from simview.utils import dialable_host, find_free_port, read_maybe_gzipped_bytes
32
34
 
33
35
  logger = logging.getLogger("simview.server")
@@ -348,8 +350,17 @@ class SimViewServer:
348
350
  # libs as immutable and everything else short-lived (max-age=60), so
349
351
  # index.html's fixed ./static/... paths never need a cache-busting
350
352
  # query param.
353
+ # Gzipped on the fly (three.js alone is ~1.1 MB raw, ~230 KB gzipped);
354
+ # applied to /static only -- /blob is float data that barely
355
+ # compresses and is served with Range support.
351
356
  self.app.mount(
352
- "/static", CacheControlStaticFiles(directory=STATIC), name="static"
357
+ "/static",
358
+ GZipMiddleware(
359
+ CacheControlStaticFiles(directory=STATIC),
360
+ minimum_size=1024,
361
+ compresslevel=6,
362
+ ),
363
+ name="static",
353
364
  )
354
365
 
355
366
  # Pre-serialized, gzipped payloads for HTTP serving. The parsed dicts are
@@ -521,7 +532,7 @@ class SimViewServer:
521
532
  def setup_routes(self):
522
533
  @self.app.get("/")
523
534
  async def index():
524
- return FileResponse(INDEX_HTML, media_type="text/html")
535
+ return HTMLResponse(render_index(INDEX_HTML, str(Path(STATIC).parent)))
525
536
 
526
537
  _gzip_headers = {"Content-Encoding": "gzip"}
527
538
 
@@ -6,7 +6,7 @@ import { AnimationController } from "./components/AnimationController.js";
6
6
  import { UI_DEFAULT_CONFIG } from "./config.js";
7
7
  import { Body } from "./objects/Body.js";
8
8
  import { Terrain } from "./objects/Terrain.js";
9
- import { BatchManager } from "./components/BatchManager.js";
9
+ import { BatchManager, batchCountOf } from "./components/BatchManager.js";
10
10
  import { ScalarPlotter } from "./ui/ScalarPlotter.js";
11
11
  import { StaticObject } from "./objects/StaticObject.js";
12
12
  import { Polyline } from "./objects/Polyline.js";
@@ -109,10 +109,18 @@ export class SimView {
109
109
  async loadData() {
110
110
  const splash = document.getElementById("loading-splash");
111
111
  const base = this.staticBase;
112
+ // Requests the page started before the modules loaded (see
113
+ // templates/index.html), each usable once. /states doesn't depend on
114
+ // the model, so it's requested alongside it instead of after
115
+ // initFromModel.
116
+ const prefetched = base ? null : window.__simviewPrefetch;
117
+ window.__simviewPrefetch = null;
118
+ const statesFetch = prefetched?.states ?? fetch(base ? `${base}/states.json` : "/states");
119
+ statesFetch.catch(() => {}); // surfaced where it's awaited below
112
120
  try {
113
121
  if (splash) splash.innerHTML = "<h1>Fetching model…</h1>";
114
122
  console.time("fetch_model");
115
- const modelResponse = await fetch(base ? `${base}/model.json` : "/model");
123
+ const modelResponse = await (prefetched?.model ?? fetch(base ? `${base}/model.json` : "/model"));
116
124
  console.timeEnd("fetch_model");
117
125
  if (!modelResponse.ok)
118
126
  throw new Error(`Failed to fetch model: ${modelResponse.status} ${modelResponse.statusText}`);
@@ -122,6 +130,13 @@ export class SimView {
122
130
  const model = await modelResponse.json();
123
131
  console.timeEnd("parse_model");
124
132
 
133
+ // The states side needs only the batch count (not the built
134
+ // scene), so its parse + blob downloads overlap the model's blobs
135
+ // and initFromModel instead of queueing behind them.
136
+ const batchCount = batchCountOf(model);
137
+ const statesReady = this.fetchStatesPayload(statesFetch, batchCount);
138
+ statesReady.catch(() => {}); // surfaced where it's awaited below
139
+
125
140
  console.time("fetch_blobs");
126
141
  await this.fetchBlobs(model);
127
142
  console.timeEnd("fetch_blobs");
@@ -130,15 +145,7 @@ export class SimView {
130
145
  this.initFromModel(model);
131
146
 
132
147
  if (splash) splash.innerHTML = "<h1>Fetching states…</h1>";
133
- console.time("fetch_states");
134
- const statesResponse = await fetch(base ? `${base}/states.json` : "/states");
135
- console.timeEnd("fetch_states");
136
- if (!statesResponse.ok)
137
- throw new Error(`Failed to fetch states: ${statesResponse.status} ${statesResponse.statusText}`);
138
-
139
- console.time("parse_states");
140
- const statesPayload = await statesResponse.json();
141
- console.timeEnd("parse_states");
148
+ const statesPayload = await statesReady;
142
149
 
143
150
  if (Array.isArray(statesPayload)) {
144
151
  // Legacy wire shape: a plain per-frame array, possibly with
@@ -154,15 +161,9 @@ export class SimView {
154
161
  } else if (statesPayload && statesPayload.version === 4) {
155
162
  // Columnar wire shape (see columnar.py::columnarize_states):
156
163
  // a lightweight index plus /blob/... URLs for the actual
157
- // whole-trajectory float32 data, fetched in parallel below.
164
+ // whole-trajectory float32 data, already fetched by
165
+ // fetchStatesPayload.
158
166
  console.debug(`Received ${statesPayload.times.length} states (columnar)`);
159
- // Long trajectories: swap the biggest current-frame-only
160
- // fields for windowed readers before the bulk fetch, so they
161
- // are never materialized in full (see utils/blobWindow.js).
162
- this.windowLargeStateFields(statesPayload);
163
- console.time("fetch_state_blobs");
164
- await this.fetchBlobs(statesPayload);
165
- console.timeEnd("fetch_state_blobs");
166
167
  this.store = new ColumnarStateStore(statesPayload, this.batchManager.simBatches);
167
168
  this.onStoreReady();
168
169
  } else {
@@ -182,6 +183,30 @@ export class SimView {
182
183
  }
183
184
  }
184
185
 
186
+ // Fetches and parses /states and, for the columnar shape, downloads its
187
+ // blobs (long trajectories' biggest current-frame-only fields are swapped
188
+ // for windowed readers first, so they are never materialized in full --
189
+ // see utils/blobWindow.js). Resolves to the payload.
190
+ async fetchStatesPayload(statesFetch, batchCount) {
191
+ console.time("fetch_states");
192
+ const statesResponse = await statesFetch;
193
+ console.timeEnd("fetch_states");
194
+ if (!statesResponse.ok)
195
+ throw new Error(`Failed to fetch states: ${statesResponse.status} ${statesResponse.statusText}`);
196
+
197
+ console.time("parse_states");
198
+ const payload = await statesResponse.json();
199
+ console.timeEnd("parse_states");
200
+
201
+ if (payload && !Array.isArray(payload) && payload.version === 4) {
202
+ this.windowLargeStateFields(payload, batchCount);
203
+ console.time("fetch_state_blobs");
204
+ await this.fetchBlobs(payload);
205
+ console.timeEnd("fetch_state_blobs");
206
+ }
207
+ return payload;
208
+ }
209
+
185
210
  // Replaces the blob URL of every large, current-frame-only per-body field
186
211
  // with a WindowedField, so fetchBlobs skips it and it's read in windows
187
212
  // around the playhead instead. Static demo mode is excluded: it serves
@@ -190,10 +215,9 @@ export class SimView {
190
215
  // bodyTransform, contacts and the scalars are deliberately untouched --
191
216
  // trails, error metrics, the terrain profile and the scalar plots all walk
192
217
  // the whole trajectory, so windowing those would just move the cost.
193
- windowLargeStateFields(statesPayload) {
218
+ windowLargeStateFields(statesPayload, batchCount) {
194
219
  if (this.staticBase) return;
195
220
  const totalFrames = statesPayload.times.length;
196
- const batchCount = this.batchManager.simBatches;
197
221
  // Overridable so tests can exercise windowing without a fixture big
198
222
  // enough to cross the real threshold (same spirit as
199
223
  // window.__debugSimView); undefined in normal use.
@@ -412,35 +436,37 @@ export class SimView {
412
436
  // appendBodyHistories has run (see BodyStateWindow.updateBodyList).
413
437
  if (this.bodyStateWindow) this.bodyStateWindow.updateBodyList();
414
438
  if (this.uiControls) this.uiControls.updateTrackBodyOptions();
415
- if (this.errorMetrics) {
416
- this.errorMetrics.onHistoryReady();
417
- }
418
- this.maybeAttachTerrainProfile();
439
+ this.maybeAttachTrajectoryPanels();
419
440
  }
420
441
 
421
- // The Terrain tab needs a body with an actual trajectory to sample
442
+ // The Error Metrics and Terrain tabs need a body with an actual trajectory to sample
422
443
  // terrain along (a static point cloud with no states doesn't count),
423
444
  // which is only known once appendBodyHistories() has filled each body's
424
- // validStates.
425
- maybeAttachTerrainProfile() {
426
- if (!this.terrain || this.terrainProfile) return;
445
+ // validStates. Error Metrics compares batches over time, so it needs the
446
+ // same plus at least two batches; a static scene gets neither tab.
447
+ maybeAttachTrajectoryPanels() {
427
448
  if (!hasBodyTrajectory(this.bodies)) return;
428
- if (!this.analysisPanel) {
429
- this.analysisPanel = new AnalysisPanel(this);
449
+ this.analysisPanel ??= new AnalysisPanel(this);
450
+ if (this.batchManager.simBatches >= 2 && !this.errorMetrics) {
451
+ this.errorMetrics = new ErrorMetrics(this);
452
+ this.errorMetrics.onHistoryReady();
453
+ this.analysisPanel.attach("errorMetrics", this.errorMetrics, this.errorMetrics.content);
454
+ }
455
+ if (this.terrain && !this.terrainProfile) {
456
+ this.terrainProfile = new TerrainProfile(this);
457
+ this.analysisPanel.attach("terrain", this.terrainProfile, this.terrainProfile.content);
430
458
  }
431
- this.terrainProfile = new TerrainProfile(this);
432
- this.analysisPanel.attach("terrain", this.terrainProfile, this.terrainProfile.content);
433
459
  }
434
460
 
435
461
  // Resolves and records position/orientation (and contacts, vectors, ...)
436
462
  // history for every frame from `startIndex` to the end of the store, for
437
463
  // trails and the error metrics panel. Each frame is materialized
438
- // transiently via store.getFrame(i) (not retained) so this works
464
+ // transiently via store.getTransformFrame(i) (not retained) so this works
439
465
  // identically whether the store is legacy or columnar.
440
466
  appendBodyHistories(startIndex) {
441
467
  if (!this.bodies || this.bodies.size === 0) return;
442
468
  for (let s = startIndex; s < this.store.length; s++) {
443
- const bodyStates = this.store.getFrame(s).bodies;
469
+ const bodyStates = this.store.getTransformFrame(s).bodies;
444
470
  if (!bodyStates) continue;
445
471
  // Resolve off this historical state's own data (not any Body's
446
472
  // current/live pose, which reflects whatever frame is currently
@@ -538,13 +564,10 @@ export class SimView {
538
564
  // so the camera's clipping/orbit range can stop being a guess.
539
565
  this.scene.applySceneExtent(this.terrain.bounds);
540
566
  const hasScalars = model.scalarNames && model.scalarNames.length > 0;
541
- const hasErrorMetrics = this.batchManager.simBatches >= 2;
542
- // The Terrain tab is attached later, from onStoreReady (see
543
- // maybeAttachTerrainProfile).
544
- if (hasScalars || hasErrorMetrics) {
545
- this.analysisPanel = new AnalysisPanel(this);
546
- }
567
+ // The Error Metrics and Terrain tabs are attached later, from
568
+ // onStoreReady (see maybeAttachTrajectoryPanels).
547
569
  if (hasScalars) {
570
+ this.analysisPanel = new AnalysisPanel(this);
548
571
  console.debug(
549
572
  "Initializing scalar plotter for scalars",
550
573
  model.scalarNames
@@ -553,10 +576,6 @@ export class SimView {
553
576
  const { tabBar, plotArea } = this.scalarPlotter;
554
577
  this.analysisPanel.attach("scalars", this.scalarPlotter, tabBar, plotArea);
555
578
  }
556
- if (hasErrorMetrics) {
557
- this.errorMetrics = new ErrorMetrics(this);
558
- this.analysisPanel.attach("errorMetrics", this.errorMetrics, this.errorMetrics.content);
559
- }
560
579
  this.interactionController = new InteractionController(this);
561
580
  this.uiControls = new UIControls(this);
562
581
  this.bodyStateWindow = new BodyStateWindow(this);
@@ -8,6 +8,14 @@ import {
8
8
  visibleBatchSet,
9
9
  } from "../utils/batchVisibility.js";
10
10
 
11
+ // The batch count a model declares (1 when absent); also what loadData needs
12
+ // before any BatchManager exists.
13
+ export function batchCountOf(modelData) {
14
+ return modelData?.simBatches !== undefined
15
+ ? Math.max(1, parseInt(modelData.simBatches))
16
+ : 1;
17
+ }
18
+
11
19
  export class BatchManager {
12
20
  constructor(app, modelData) {
13
21
  this.app = app;
@@ -34,7 +42,7 @@ export class BatchManager {
34
42
 
35
43
  // Set batch count from model data
36
44
  if (modelData.simBatches !== undefined) {
37
- this.simBatches = Math.max(1, parseInt(modelData.simBatches));
45
+ this.simBatches = batchCountOf(modelData);
38
46
  console.log(
39
47
  `Initializing with ${this.simBatches} simulation batches`
40
48
  );
@@ -103,7 +103,7 @@ export class InteractionController {
103
103
  const similarityActive = this.app.uiState?.pointColorMode === "similarity";
104
104
  if (!probeActive && !similarityActive) return;
105
105
 
106
- this.raycaster.setFromCamera(this.mouse, this.app.scene.camera);
106
+ this.#setRayFromClick(e);
107
107
  // THREE's raycaster ignores `visible`, so hidden objects (a focused-
108
108
  // mode batch's point cloud that was built earlier, a hidden body) are
109
109
  // filtered out here or a click lands on something not on screen.
@@ -162,6 +162,36 @@ export class InteractionController {
162
162
  this.hideTerrainTooltip();
163
163
  }
164
164
 
165
+ // In split screen each half is rendered with the camera shifted to its
166
+ // batch and a half-width aspect (Scene.animate); raycast the same way, or
167
+ // a click in either half picks whatever sits under it in the full view.
168
+ #setRayFromClick(e) {
169
+ const app = this.app;
170
+ const camera = app.scene.camera;
171
+ const bm = app.batchManager;
172
+ if (!(app.uiState?.splitScreen && bm && bm.simBatches >= 2)) {
173
+ this.raycaster.setFromCamera(this.mouse, camera);
174
+ return;
175
+ }
176
+ const width = window.innerWidth;
177
+ const height = window.innerHeight;
178
+ const right = e.clientX >= width / 2;
179
+ const batch = right ? (app.uiState.splitBatchB ?? 1) : (app.uiState.splitBatchA ?? 0);
180
+ const offset = bm.getBatchOffset(batch);
181
+ const active = bm.getBatchOffset(bm.currentlyActiveBatch);
182
+ const delta = [offset.x - active.x, offset.y - active.y, offset.z - active.z];
183
+ const ndc = this.mouse.clone();
184
+ ndc.x = ((e.clientX - (right ? width / 2 : 0)) / (width / 2)) * 2 - 1;
185
+ const cam = camera.clone();
186
+ cam.aspect = width / 2 / height;
187
+ cam.updateProjectionMatrix();
188
+ cam.position.x += delta[0];
189
+ cam.position.y += delta[1];
190
+ cam.position.z += delta[2];
191
+ cam.updateMatrixWorld();
192
+ this.raycaster.setFromCamera(ndc, cam);
193
+ }
194
+
165
195
  // Point-cloud analog of showTerrainTooltip: recolors the whole body by
166
196
  // cosine similarity to the clicked point instead of showing a props
167
197
  // tooltip (there's no single "value" to display -- the whole point of
@@ -170,6 +200,13 @@ export class InteractionController {
170
200
  const body = this.app.bodies.get(hit.object.userData.bodyName);
171
201
  if (!body) return;
172
202
  body.recolorBySimilarity(hit.index);
203
+ if (this.app.uiState?.linkPointSimilarity) {
204
+ for (const other of this.app.bodies.values()) {
205
+ if (other !== body && other.pointEmbedding && other.pointCount === body.pointCount) {
206
+ other.recolorBySimilarity(hit.index);
207
+ }
208
+ }
209
+ }
173
210
  this.#hideTooltipText();
174
211
  if (this.probeSphere) {
175
212
  this.probeSphere.position.copy(hit.point);
@@ -16,6 +16,51 @@ export class Scene {
16
16
  this.initScene();
17
17
  this.minRenderDelay = 1000 / FREQ_CONFIG.scene;
18
18
  this.lastRenderTime = Number.NEGATIVE_INFINITY;
19
+ this.setupInvalidation();
20
+ }
21
+
22
+ // The canvas only needs redrawing when something may have changed.
23
+ // Mutations are scattered (GUI toggles, panels, data landing), so rather
24
+ // than hooking each one, any user input or camera move marks the scene
25
+ // dirty, playback/recording/new frames always render, and an idle
26
+ // heartbeat repaints anything else (e.g. a Range window landing while
27
+ // paused) within IDLE_RENDER_MS.
28
+ static IDLE_RENDER_MS = 250;
29
+ invalidate() {
30
+ this.needsRender = true;
31
+ }
32
+
33
+ setupInvalidation() {
34
+ this.needsRender = true;
35
+ this._lastFrameIndex = null;
36
+ const mark = () => this.invalidate();
37
+ // pointermove only while a button is held: drags orbit/pan the camera.
38
+ this._onInput = (e) => {
39
+ if (e.type !== "pointermove" || e.buttons) this.invalidate();
40
+ };
41
+ this._inputEvents = [
42
+ "pointerdown", "pointermove", "pointerup", "wheel",
43
+ "keydown", "keyup", "input", "change", "click",
44
+ ];
45
+ this._inputEvents.forEach((t) =>
46
+ window.addEventListener(t, this._onInput, { capture: true, passive: true })
47
+ );
48
+ this.controls.addEventListener("change", mark);
49
+ }
50
+
51
+ #shouldRender(now) {
52
+ const ac = this.app.animationController;
53
+ if (
54
+ this.needsRender ||
55
+ ac?.isPlaying ||
56
+ ac?.isRecording ||
57
+ ac?.currentStateIndex !== this._lastFrameIndex ||
58
+ now - this.lastRenderTime >= Scene.IDLE_RENDER_MS
59
+ ) {
60
+ this._lastFrameIndex = ac?.currentStateIndex;
61
+ return true;
62
+ }
63
+ return false;
19
64
  }
20
65
 
21
66
  initScene() {
@@ -67,12 +112,17 @@ export class Scene {
67
112
  window.removeEventListener("resize", this._onResize);
68
113
  this._onResize = null;
69
114
  }
115
+ this._inputEvents?.forEach((t) =>
116
+ window.removeEventListener(t, this._onInput, { capture: true })
117
+ );
118
+ this._inputEvents = null;
70
119
  this.controls?.dispose();
71
120
  this.renderer?.dispose();
72
121
  this.renderer?.domElement?.remove();
73
122
  }
74
123
 
75
124
  #handleWindowResize() {
125
+ this.invalidate(); // resizing clears the canvas
76
126
  this.camera.aspect = window.innerWidth / window.innerHeight;
77
127
  this.camera.updateProjectionMatrix();
78
128
  this.renderer.setPixelRatio(window.devicePixelRatio);
@@ -139,7 +189,11 @@ export class Scene {
139
189
  // and B side by side, shifting the camera by each batch's offset from the
140
190
  // active one for its half of the viewport.
141
191
  animate(now) {
142
- if (now - this.lastRenderTime < this.minRenderDelay) return;
192
+ // The -1 absorbs rAF timestamp jitter: at 60 Hz the deltas hover
193
+ // around 16.67 ms and would otherwise drop every other frame.
194
+ if (now - this.lastRenderTime < this.minRenderDelay - 1) return;
195
+ if (!this.#shouldRender(now)) return;
196
+ this.needsRender = false;
143
197
 
144
198
  if (this.app.uiState && this.app.uiState.splitScreen && this.app.batchManager && this.app.batchManager.simBatches >= 2) {
145
199
  const batchA = this.app.uiState.splitBatchA !== undefined ? this.app.uiState.splitBatchA : 0;
@@ -167,6 +167,25 @@ export class ColumnarStateStore {
167
167
  return state;
168
168
  }
169
169
 
170
+ // Frame `i` carrying only each body's bodyTransform. For whole-run walks
171
+ // (trail/error-metric histories) that never read the windowed fields:
172
+ // getFrame() would start a Range fetch for every window of every one.
173
+ getTransformFrame(i) {
174
+ const bodies = [];
175
+ for (const body of this._bodies) {
176
+ const value = body.fields.bodyTransform;
177
+ const entry = { name: body.name };
178
+ if (value && typeof value.rowsAt === "function") {
179
+ const rows = value.rowsAt(i);
180
+ if (rows) entry.bodyTransform = rows;
181
+ } else if (value) {
182
+ entry.bodyTransform = this._sliceField(value, COLUMNAR_FIELD_WIDTHS.bodyTransform, i);
183
+ }
184
+ bodies.push(entry);
185
+ }
186
+ return { time: this.times[i], bodies };
187
+ }
188
+
170
189
  // Per-batch series for the scalar plotter: one per-frame value array per
171
190
  // batch, indexed like `times`.
172
191
  // `simBatches` is accepted (and ignored) for API parity with
@@ -217,6 +236,10 @@ export class LegacyStateStore {
217
236
  return this._states[i];
218
237
  }
219
238
 
239
+ getTransformFrame(i) {
240
+ return this._states[i];
241
+ }
242
+
220
243
  // `simBatches` is passed explicitly: the legacy shape records no batch
221
244
  // count of its own (callers use app.batchManager.simBatches).
222
245
  getScalarSeries(name, simBatches) {
@@ -44,7 +44,8 @@ export const UI_DEFAULT_CONFIG = {
44
44
  terrainColorMap: "magma", // Default colormap
45
45
  terrainColorMode: "height", // "height", or any named terrain property (e.g. friction, stiffness)
46
46
  terrainProbe: false, // interactive terrain probe on click
47
- pointColorMode: "pca", // "pca" or "similarity" (point clouds with embeddings)
47
+ pointColorMode: "pca", // "pca", "similarity" (point clouds with embeddings) or a color layer name
48
+ linkPointSimilarity: false, // a point click recolors every same-size point cloud
48
49
  };
49
50
 
50
51
  export const FREQ_CONFIG = {