simview 6.4.0__tar.gz → 6.4.1__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 (112) hide show
  1. {simview-6.4.0/simview.egg-info → simview-6.4.1}/PKG-INFO +1 -1
  2. {simview-6.4.0 → simview-6.4.1}/pyproject.toml +1 -1
  3. {simview-6.4.0 → simview-6.4.1}/simview/__main__.py +5 -5
  4. {simview-6.4.0 → simview-6.4.1}/simview/columnar.py +3 -2
  5. {simview-6.4.0 → simview-6.4.1}/simview/launcher.py +1 -0
  6. {simview-6.4.0 → simview-6.4.1}/simview/merge.py +22 -19
  7. {simview-6.4.0 → simview-6.4.1}/simview/remote.py +1 -1
  8. {simview-6.4.0 → simview-6.4.1}/simview/render.py +6 -0
  9. {simview-6.4.0 → simview-6.4.1}/simview/scene.py +14 -12
  10. {simview-6.4.0 → simview-6.4.1}/simview/server.py +58 -11
  11. {simview-6.4.0 → simview-6.4.1}/simview/static/js/SimView.js +56 -21
  12. {simview-6.4.0 → simview-6.4.1}/simview/static/js/components/AnimationController.js +7 -2
  13. {simview-6.4.0 → simview-6.4.1}/simview/static/js/components/WindowedField.js +12 -0
  14. {simview-6.4.0 → simview-6.4.1}/simview/static/js/objects/Body.js +34 -17
  15. {simview-6.4.0 → simview-6.4.1}/simview/static/js/objects/StaticObject.js +21 -4
  16. {simview-6.4.0 → simview-6.4.1}/simview/static/js/objects/Terrain.js +88 -19
  17. {simview-6.4.0 → simview-6.4.1}/simview/static/js/objects/utils.js +8 -0
  18. {simview-6.4.0 → simview-6.4.1}/simview/static/js/ui/ScalarPlotter.js +4 -4
  19. {simview-6.4.0 → simview-6.4.1}/simview/static/js/ui/TerrainProfile.js +6 -0
  20. {simview-6.4.0 → simview-6.4.1}/simview/static/js/utils/csv.js +4 -1
  21. {simview-6.4.0 → simview-6.4.1}/simview/static/js/utils/liveFollow.js +10 -0
  22. {simview-6.4.0 → simview-6.4.1}/simview/static/js/utils/terrainSample.js +4 -4
  23. {simview-6.4.0 → simview-6.4.1}/simview/terrain.py +7 -2
  24. {simview-6.4.0 → simview-6.4.1}/simview/utils.py +33 -0
  25. {simview-6.4.0 → simview-6.4.1/simview.egg-info}/PKG-INFO +1 -1
  26. {simview-6.4.0 → simview-6.4.1}/simview.egg-info/SOURCES.txt +1 -0
  27. {simview-6.4.0 → simview-6.4.1}/tests/test_launcher.py +19 -0
  28. {simview-6.4.0 → simview-6.4.1}/tests/test_merge.py +44 -0
  29. {simview-6.4.0 → simview-6.4.1}/tests/test_remote.py +2 -0
  30. {simview-6.4.0 → simview-6.4.1}/tests/test_server.py +20 -0
  31. {simview-6.4.0 → simview-6.4.1}/tests/test_show.py +11 -0
  32. simview-6.4.1/tests/test_strict_json.py +100 -0
  33. {simview-6.4.0 → simview-6.4.1}/tests/test_terrain_query.py +15 -0
  34. {simview-6.4.0 → simview-6.4.1}/LICENSE +0 -0
  35. {simview-6.4.0 → simview-6.4.1}/MANIFEST.in +0 -0
  36. {simview-6.4.0 → simview-6.4.1}/README.md +0 -0
  37. {simview-6.4.0 → simview-6.4.1}/setup.cfg +0 -0
  38. {simview-6.4.0 → simview-6.4.1}/simview/__init__.py +0 -0
  39. {simview-6.4.0 → simview-6.4.1}/simview/diff.py +0 -0
  40. {simview-6.4.0 → simview-6.4.1}/simview/info.py +0 -0
  41. {simview-6.4.0 → simview-6.4.1}/simview/live.py +0 -0
  42. {simview-6.4.0 → simview-6.4.1}/simview/model.py +0 -0
  43. {simview-6.4.0 → simview-6.4.1}/simview/preload.py +0 -0
  44. {simview-6.4.0 → simview-6.4.1}/simview/py.typed +0 -0
  45. {simview-6.4.0 → simview-6.4.1}/simview/state.py +0 -0
  46. {simview-6.4.0 → simview-6.4.1}/simview/static/css/controls.css +0 -0
  47. {simview-6.4.0 → simview-6.4.1}/simview/static/js/components/BatchManager.js +0 -0
  48. {simview-6.4.0 → simview-6.4.1}/simview/static/js/components/InteractionController.js +0 -0
  49. {simview-6.4.0 → simview-6.4.1}/simview/static/js/components/Scene.js +0 -0
  50. {simview-6.4.0 → simview-6.4.1}/simview/static/js/components/StateStore.js +0 -0
  51. {simview-6.4.0 → simview-6.4.1}/simview/static/js/config.js +0 -0
  52. {simview-6.4.0 → simview-6.4.1}/simview/static/js/main.js +0 -0
  53. {simview-6.4.0 → simview-6.4.1}/simview/static/js/objects/Polyline.js +0 -0
  54. {simview-6.4.0 → simview-6.4.1}/simview/static/js/objects/colormap.js +0 -0
  55. {simview-6.4.0 → simview-6.4.1}/simview/static/js/objects/similarity.js +0 -0
  56. {simview-6.4.0 → simview-6.4.1}/simview/static/js/ui/AnalysisPanel.js +0 -0
  57. {simview-6.4.0 → simview-6.4.1}/simview/static/js/ui/BatchLegend.js +0 -0
  58. {simview-6.4.0 → simview-6.4.1}/simview/static/js/ui/BodyStateWindow.js +0 -0
  59. {simview-6.4.0 → simview-6.4.1}/simview/static/js/ui/Controls.js +0 -0
  60. {simview-6.4.0 → simview-6.4.1}/simview/static/js/ui/ErrorMetrics.js +0 -0
  61. {simview-6.4.0 → simview-6.4.1}/simview/static/js/ui/Legend.js +0 -0
  62. {simview-6.4.0 → simview-6.4.1}/simview/static/js/ui/PlaybackControls.js +0 -0
  63. {simview-6.4.0 → simview-6.4.1}/simview/static/js/ui/chartControls.js +0 -0
  64. {simview-6.4.0 → simview-6.4.1}/simview/static/js/utils/batchPresets.js +0 -0
  65. {simview-6.4.0 → simview-6.4.1}/simview/static/js/utils/batchVisibility.js +0 -0
  66. {simview-6.4.0 → simview-6.4.1}/simview/static/js/utils/blobCodec.js +0 -0
  67. {simview-6.4.0 → simview-6.4.1}/simview/static/js/utils/blobWindow.js +0 -0
  68. {simview-6.4.0 → simview-6.4.1}/simview/static/js/utils/bodyTransforms.js +0 -0
  69. {simview-6.4.0 → simview-6.4.1}/simview/static/js/utils/cameraRange.js +0 -0
  70. {simview-6.4.0 → simview-6.4.1}/simview/static/js/utils/episodes.js +0 -0
  71. {simview-6.4.0 → simview-6.4.1}/simview/static/js/utils/errorMath.js +0 -0
  72. {simview-6.4.0 → simview-6.4.1}/simview/static/js/utils/html.js +0 -0
  73. {simview-6.4.0 → simview-6.4.1}/simview/static/js/utils/interpolate.js +0 -0
  74. {simview-6.4.0 → simview-6.4.1}/simview/static/js/utils/keyboard.js +0 -0
  75. {simview-6.4.0 → simview-6.4.1}/simview/static/js/utils/scalarSeries.js +0 -0
  76. {simview-6.4.0 → simview-6.4.1}/simview/static/js/utils/uplot.js +0 -0
  77. {simview-6.4.0 → simview-6.4.1}/simview/static/js/utils/viewState.js +0 -0
  78. {simview-6.4.0 → simview-6.4.1}/simview/static/js/utils/viewerDefaults.js +0 -0
  79. {simview-6.4.0 → simview-6.4.1}/simview/static/js/utils/visibleRanges.js +0 -0
  80. {simview-6.4.0 → simview-6.4.1}/simview/static/js/vendor/js-colormaps.js +0 -0
  81. {simview-6.4.0 → simview-6.4.1}/simview/static/lib/three-0.174.0/addons/controls/OrbitControls.js +0 -0
  82. {simview-6.4.0 → simview-6.4.1}/simview/static/lib/three-0.174.0/addons/libs/lil-gui.module.min.js +0 -0
  83. {simview-6.4.0 → simview-6.4.1}/simview/static/lib/three-0.174.0/three.core.js +0 -0
  84. {simview-6.4.0 → simview-6.4.1}/simview/static/lib/three-0.174.0/three.module.js +0 -0
  85. {simview-6.4.0 → simview-6.4.1}/simview/static/lib/uPlot-1.6.32/uPlot.esm.js +0 -0
  86. {simview-6.4.0 → simview-6.4.1}/simview/static/lib/uPlot-1.6.32/uPlot.min.css +0 -0
  87. {simview-6.4.0 → simview-6.4.1}/simview/static/textures/contacts/red-cross0.png +0 -0
  88. {simview-6.4.0 → simview-6.4.1}/simview/static/textures/points/ball1.png +0 -0
  89. {simview-6.4.0 → simview-6.4.1}/simview/templates/index.html +0 -0
  90. {simview-6.4.0 → simview-6.4.1}/simview/view.py +0 -0
  91. {simview-6.4.0 → simview-6.4.1}/simview.egg-info/dependency_links.txt +0 -0
  92. {simview-6.4.0 → simview-6.4.1}/simview.egg-info/entry_points.txt +0 -0
  93. {simview-6.4.0 → simview-6.4.1}/simview.egg-info/requires.txt +0 -0
  94. {simview-6.4.0 → simview-6.4.1}/simview.egg-info/top_level.txt +0 -0
  95. {simview-6.4.0 → simview-6.4.1}/tests/test_batch_selection.py +0 -0
  96. {simview-6.4.0 → simview-6.4.1}/tests/test_cli.py +0 -0
  97. {simview-6.4.0 → simview-6.4.1}/tests/test_columnar_ondisk.py +0 -0
  98. {simview-6.4.0 → simview-6.4.1}/tests/test_columnar_states.py +0 -0
  99. {simview-6.4.0 → simview-6.4.1}/tests/test_contacts.py +0 -0
  100. {simview-6.4.0 → simview-6.4.1}/tests/test_diff.py +0 -0
  101. {simview-6.4.0 → simview-6.4.1}/tests/test_embed_defaults.py +0 -0
  102. {simview-6.4.0 → simview-6.4.1}/tests/test_episodes.py +0 -0
  103. {simview-6.4.0 → simview-6.4.1}/tests/test_info.py +0 -0
  104. {simview-6.4.0 → simview-6.4.1}/tests/test_live.py +0 -0
  105. {simview-6.4.0 → simview-6.4.1}/tests/test_pointcloud_features.py +0 -0
  106. {simview-6.4.0 → simview-6.4.1}/tests/test_preload.py +0 -0
  107. {simview-6.4.0 → simview-6.4.1}/tests/test_roundtrip.py +0 -0
  108. {simview-6.4.0 → simview-6.4.1}/tests/test_scene.py +0 -0
  109. {simview-6.4.0 → simview-6.4.1}/tests/test_terrain.py +0 -0
  110. {simview-6.4.0 → simview-6.4.1}/tests/test_trajectory.py +0 -0
  111. {simview-6.4.0 → simview-6.4.1}/tests/test_utils.py +0 -0
  112. {simview-6.4.0 → simview-6.4.1}/tests/test_view.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: simview
3
- Version: 6.4.0
3
+ Version: 6.4.1
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.4.0"
7
+ version = "6.4.1"
8
8
  readme = "README.md"
9
9
  requires-python = ">=3.12"
10
10
  license = "BSD-3-Clause"
@@ -10,7 +10,7 @@ from pathlib import Path
10
10
 
11
11
  from simview import CACHE_DIR, __version__, remote
12
12
  from simview.server import SimViewServer
13
- from simview.utils import human_bytes, load_scene, load_scene_model
13
+ from simview.utils import dumps_json, human_bytes, load_scene, load_scene_model
14
14
 
15
15
  logger = logging.getLogger("simview.cli")
16
16
 
@@ -104,7 +104,7 @@ def run_info(path: Path, as_json: bool) -> None:
104
104
  sys.exit(1)
105
105
 
106
106
  if as_json:
107
- print(json.dumps(summary, indent=2))
107
+ print(dumps_json(summary, indent=2))
108
108
  else:
109
109
  print(format_text(summary))
110
110
 
@@ -196,7 +196,7 @@ def run_terrain(path: Path, args: argparse.Namespace) -> None:
196
196
  if args.csv:
197
197
  print(csv_fn(result), end="")
198
198
  elif args.json:
199
- print(json.dumps(result, indent=2))
199
+ print(dumps_json(result, indent=2))
200
200
  else:
201
201
  print(text_fn(result))
202
202
 
@@ -246,7 +246,7 @@ def run_diff(path: Path, args: argparse.Namespace) -> None:
246
246
  if args.csv:
247
247
  print(diff_mod.format_diff_csv(result), end="")
248
248
  elif args.json:
249
- print(json.dumps(result, indent=2))
249
+ print(dumps_json(result, indent=2))
250
250
  else:
251
251
  print(diff_mod.format_diff_text(result))
252
252
 
@@ -315,7 +315,7 @@ def save_merged(
315
315
  columnar_states = columnarize_states(merged["states"], merged["model"], inline_blob)
316
316
  if columnar_states is not None:
317
317
  merged["states"] = columnar_states
318
- payload = json.dumps(merged).encode("utf-8")
318
+ payload = dumps_json(merged).encode("utf-8")
319
319
  if out_path.suffix == ".gz":
320
320
  payload = gzip.compress(payload, compresslevel=1)
321
321
  try:
@@ -466,9 +466,10 @@ def write_static_bundle(data: dict, directory) -> None:
466
466
  ``model.json``, ``states.json`` and raw ``blob/<id>`` files, with blob
467
467
  references rewritten to ``/blob/<id>`` (the viewer maps these to
468
468
  ``<base>/blob/<id>``). Stdlib-only."""
469
- import json
470
469
  from pathlib import Path
471
470
 
471
+ from simview.utils import dumps_json
472
+
472
473
  out = Path(directory)
473
474
  (out / "blob").mkdir(parents=True, exist_ok=True)
474
475
  count = 0
@@ -486,4 +487,4 @@ def write_static_bundle(data: dict, directory) -> None:
486
487
  if is_columnar(data["states"]):
487
488
  rewrite_blobs(data["states"], write_blob)
488
489
  for name in ("model", "states"):
489
- (out / f"{name}.json").write_text(json.dumps(data[name]))
490
+ (out / f"{name}.json").write_text(dumps_json(data[name]))
@@ -59,6 +59,7 @@ class SimViewLauncher:
59
59
  # Serialize the scene once and hand it to the server directly,
60
60
  # avoiding a temp-file write + read-back round-trip.
61
61
  logger.info("SimViewLauncher: Serving in-memory SimulationScene")
62
+ self._scene._prepare_for_output()
62
63
  data = {
63
64
  "model": self._scene.model.to_json(),
64
65
  "states": self._scene.states,
@@ -23,8 +23,6 @@ import re
23
23
  from pathlib import Path
24
24
  from typing import Sequence
25
25
 
26
- import orjson
27
-
28
26
  from .columnar import (
29
27
  STATE_FIELD_WIDTHS,
30
28
  batch_rows,
@@ -34,7 +32,7 @@ from .columnar import (
34
32
  is_blob,
35
33
  is_columnar,
36
34
  )
37
- from .utils import bodies_by_name, read_maybe_gzipped_bytes
35
+ from .utils import bodies_by_name, loads_json, read_maybe_gzipped_bytes
38
36
 
39
37
  logger = logging.getLogger("simview.merge")
40
38
 
@@ -230,7 +228,7 @@ def _decode_per_batch(
230
228
 
231
229
  def _load_json(path: Path) -> dict:
232
230
  raw = read_maybe_gzipped_bytes(path)
233
- doc = orjson.loads(raw)
231
+ doc = loads_json(raw)
234
232
  # Merging works frame by frame (resampling onto the first file's timeline),
235
233
  # so a columnar file is expanded to the per-frame layout up front rather
236
234
  # than teaching every step below a second shape. expand_columnar_states is
@@ -758,12 +756,11 @@ def _merge_states(
758
756
  )
759
757
  )
760
758
  if contacts is not None:
761
- if "contacts" not in body_state:
762
- raise ValueError(
763
- f"'{labels[file_idx]}' body '{name}' declares 'contacts' as "
764
- f"available but is missing it at t={states[state_idx]['time']}."
765
- )
766
- contacts.extend(_select(body_state["contacts"], selection))
759
+ # A frame may omit contacts (save/view treat that as none).
760
+ body_contacts = body_state.get("contacts")
761
+ if body_contacts is None:
762
+ body_contacts = [[] for _ in range(batch_size)]
763
+ contacts.extend(_select(body_contacts, selection))
767
764
 
768
765
  transform = field_values["bodyTransform"]
769
766
  if len(transform) != total_batches:
@@ -858,13 +855,13 @@ def merge_simulation_files(
858
855
  # file's batch count), so they only pass through unchanged when nothing
859
856
  # about the batch layout changes.
860
857
  polylines = models[0].get("polylines") or []
861
- if polylines and (
862
- len(models) > 1 or any(sel is not None for sel in batch_selections)
863
- ):
864
- raise ValueError(
865
- f"'{labels[0]}' has polylines, which cannot be merged across files "
866
- "or batch selections; drop them before merging."
867
- )
858
+ if len(models) > 1 or any(sel is not None for sel in batch_selections):
859
+ for model, label in zip(models, labels):
860
+ if model.get("polylines"):
861
+ raise ValueError(
862
+ f"'{label}' has polylines, which cannot be merged across "
863
+ "files or batch selections; drop them before merging."
864
+ )
868
865
  merged_states = _merge_states(
869
866
  states_list, batch_sizes, bodies, scalar_names, labels, batch_selections
870
867
  )
@@ -916,9 +913,15 @@ def merge_simulation_files(
916
913
  # Keep every input's run provenance (engine, checkpoint, git commit, ...)
917
914
  # instead of silently dropping it -- namespaced per source file since the
918
915
  # inputs may come from entirely different runs.
916
+ # Basenames can collide ('a/run.json', 'b/run.json'), so a duplicate is
917
+ # keyed by its path as given, then also by input position.
918
+ source_keys: list[str] = []
919
+ for i, (path, label) in enumerate(zip(resolved_paths, labels)):
920
+ key = label if labels.count(label) == 1 else str(path)
921
+ source_keys.append(key if key not in source_keys else f"{key} [{i}]")
919
922
  source_metadata = {
920
- label: model["metadata"]
921
- for model, label in zip(models, labels)
923
+ key: model["metadata"]
924
+ for model, key in zip(models, source_keys)
922
925
  if model.get("metadata") is not None
923
926
  }
924
927
  if source_metadata:
@@ -148,7 +148,7 @@ def quote_remote_path(path: str) -> str:
148
148
  user name) and only the remainder is quoted.
149
149
  """
150
150
  head, sep, tail = path.partition("/")
151
- if sep and _TILDE_RE.match(head):
151
+ if _TILDE_RE.match(head):
152
152
  return head + sep + (shlex.quote(tail) if tail else "")
153
153
  return shlex.quote(path)
154
154
 
@@ -92,6 +92,12 @@ def render_screenshot(
92
92
  "#loading-splash", state="detached", timeout=_LOAD_TIMEOUT_MS
93
93
  )
94
94
  page.wait_for_timeout(_SETTLE_DELAY_MS)
95
+ # A view in a terrain property color mode fetches that layer on
96
+ # demand (Terrain.loadProperty); let it land and repaint.
97
+ if page.evaluate(
98
+ "async () => (await window.__debugSimView?.terrain?.propertyLoadsSettled())?.length"
99
+ ):
100
+ page.wait_for_timeout(_SETTLE_DELAY_MS)
95
101
  output_path.parent.mkdir(parents=True, exist_ok=True)
96
102
  page.screenshot(path=str(output_path))
97
103
  finally:
@@ -36,7 +36,7 @@ from .state import (
36
36
  LocalTransformLike,
37
37
  SimViewBodyState,
38
38
  )
39
- from .utils import iter_names, read_maybe_gzipped_bytes
39
+ from .utils import dumps_json, iter_names, read_maybe_gzipped_bytes
40
40
 
41
41
  logger = logging.getLogger("simview.scene")
42
42
 
@@ -455,6 +455,13 @@ class SimulationScene:
455
455
  state[name] = arr[t].tolist()
456
456
  self.states.append(state)
457
457
 
458
+ def _prepare_for_output(self) -> None:
459
+ """Validate and reconcile the model against the states before it is
460
+ serialized: shared by `save()`, `show()` and `SimViewLauncher`."""
461
+ self._check_episodes_in_range()
462
+ self._check_polyline_frames()
463
+ self.reconcile_available_attributes()
464
+
458
465
  def _check_episodes_in_range(self) -> None:
459
466
  """Every episode must start at a frame this scene actually has."""
460
467
  for episode in self.model.episodes or []:
@@ -545,9 +552,7 @@ class SimulationScene:
545
552
  raise ValueError(
546
553
  "Cannot save data: The simulation model is not complete (e.g., terrain might be missing)."
547
554
  )
548
- self._check_episodes_in_range()
549
- self._check_polyline_frames()
550
- self.reconcile_available_attributes()
555
+ self._prepare_for_output()
551
556
 
552
557
  output_path = Path(filepath)
553
558
  if compress and output_path.suffix != ".gz":
@@ -571,11 +576,11 @@ class SimulationScene:
571
576
  with (gzip.open if compress else open)(output_path, "wt") as f:
572
577
  f.write("{\n")
573
578
  f.write(' "model": ')
574
- json.dump(model_json, f, indent=2)
579
+ f.write(dumps_json(model_json, indent=2))
575
580
  f.write(",\n")
576
581
  if columnar_states is not None:
577
582
  f.write(' "states": ')
578
- json.dump(columnar_states, f)
583
+ f.write(dumps_json(columnar_states))
579
584
  f.write("\n}")
580
585
  else:
581
586
  # Streamed frame by frame: the per-frame layout is only
@@ -586,7 +591,7 @@ class SimulationScene:
586
591
  if i > 0:
587
592
  f.write(",\n")
588
593
  f.write(" ")
589
- json.dump(state, f)
594
+ f.write(dumps_json(state))
590
595
  f.write("\n ]\n}")
591
596
  logger.info("Simulation data successfully saved to %s", output_path)
592
597
 
@@ -637,9 +642,7 @@ class SimulationScene:
637
642
  "Cannot show scene: the simulation model is not complete "
638
643
  "(e.g. terrain might be missing)."
639
644
  )
640
- self._check_episodes_in_range()
641
- self._check_polyline_frames()
642
- self.reconcile_available_attributes()
645
+ self._prepare_for_output()
643
646
 
644
647
  data = {"model": self.model.to_json(), "states": self.states}
645
648
  handle = ViewerHandle(
@@ -678,8 +681,7 @@ class SimulationScene:
678
681
  computed from the heightmap gradients, unless `compute_normals=False`,
679
682
  which stores no normals at all (three floats per cell less on disk and
680
683
  over the wire). The viewer then shades the surface from normals it
681
- computes itself, and the "normals" arrow visualization has nothing to
682
- draw.
684
+ computes itself, and draws the "normals" arrows from those too.
683
685
 
684
686
  `x_lim`/`y_lim` are the `(min, max)` coordinates of the X/Y axes.
685
687
  `grid_res` is the spacing between adjacent grid nodes; if `x_lim` and
@@ -4,6 +4,7 @@ import asyncio
4
4
  import copy
5
5
  import gzip
6
6
  import hashlib
7
+ import html
7
8
  import json
8
9
  import logging
9
10
  import os
@@ -30,7 +31,13 @@ from starlette.types import Scope
30
31
 
31
32
  from simview.columnar import columnarize_states, is_columnar, rewrite_blobs
32
33
  from simview.preload import render_index
33
- from simview.utils import dialable_host, find_free_port, read_maybe_gzipped_bytes
34
+ from simview.utils import (
35
+ dialable_host,
36
+ dumps_json,
37
+ find_free_port,
38
+ loads_json,
39
+ read_maybe_gzipped_bytes,
40
+ )
34
41
 
35
42
  logger = logging.getLogger("simview.server")
36
43
 
@@ -187,10 +194,41 @@ def _ws_origin_allowed(websocket: WebSocket) -> bool:
187
194
  host_header = websocket.headers.get("host", "")
188
195
  if match.group(1) != host_header:
189
196
  return False
197
+ return _host_allowed(host_header)
198
+
199
+
200
+ def _host_allowed(host_header: str) -> bool:
201
+ """Whether a Host header names 'localhost' or an address -- anything else
202
+ may be an attacker's DNS-rebound name (see _ws_origin_allowed)."""
190
203
  host = _host_of(host_header)
191
204
  return host == "localhost" or _IP_LITERAL_RE.match(host) is not None
192
205
 
193
206
 
207
+ class _HostCheckMiddleware:
208
+ """Rejects HTTP requests whose Host isn't 'localhost' or an address.
209
+
210
+ The DNS-rebinding guard for the HTTP routes, the same Host rule
211
+ _ws_origin_allowed applies: after a rebind an attacker's page is
212
+ same-origin with the server, so CORS no longer stops it reading /model
213
+ (which carries the blob token) or POSTing /batch-names. A request with no
214
+ Host header (HTTP/1.0 tooling) is let through; browsers always send one.
215
+ """
216
+
217
+ def __init__(self, app):
218
+ self.app = app
219
+
220
+ async def __call__(self, scope: Scope, receive, send):
221
+ if scope["type"] == "http":
222
+ host_header = Headers(scope=scope).get("host")
223
+ if host_header is not None and not _host_allowed(host_header):
224
+ response = JSONResponse(
225
+ {"message": "Invalid Host header"}, status_code=400
226
+ )
227
+ await response(scope, receive, send)
228
+ return
229
+ await self.app(scope, receive, send)
230
+
231
+
194
232
  class _BodySizeLimitMiddleware:
195
233
  """Rejects requests whose declared body exceeds _MAX_REQUEST_BODY_BYTES.
196
234
 
@@ -317,6 +355,10 @@ class SimViewServer:
317
355
  self.sim_path = self.sim_paths[0] if self.sim_paths else None
318
356
  self._preloaded_data = data
319
357
  self.model_data = None
358
+ # Serializes model_data mutate+repack: the producer thread
359
+ # (set_episodes) and the event loop (/batch-names) both repack, and
360
+ # gzip releases the GIL, so an older snapshot could land last.
361
+ self._model_lock = threading.Lock()
320
362
 
321
363
  @asynccontextmanager
322
364
  async def lifespan(app: FastAPI):
@@ -343,6 +385,8 @@ class SimViewServer:
343
385
  # CORS above, so it wraps it and rejects oversized payloads before any
344
386
  # middleware or handler runs.
345
387
  self.app.add_middleware(_BodySizeLimitMiddleware)
388
+ # Outermost: refuse DNS-rebound requests before anything else runs.
389
+ self.app.add_middleware(_HostCheckMiddleware)
346
390
 
347
391
  # Mount static files. StaticFiles adds ETag/Last-Modified headers so
348
392
  # unchanged assets (vendored libs, textures, our own JS) are served
@@ -412,7 +456,7 @@ class SimViewServer:
412
456
  assert self.sim_path is not None
413
457
  logger.info("Loading simulation data from %s...", self.sim_path)
414
458
  raw = read_maybe_gzipped_bytes(self.sim_path)
415
- data = orjson.loads(raw)
459
+ data = loads_json(raw)
416
460
 
417
461
  model_data = data.get("model")
418
462
  states_data = data.get("states")
@@ -621,8 +665,9 @@ class SimViewServer:
621
665
  status_code=400,
622
666
  )
623
667
 
624
- self.model_data["batchNames"] = names
625
- self._pack_model()
668
+ with self._model_lock:
669
+ self.model_data["batchNames"] = names
670
+ self._pack_model()
626
671
 
627
672
  names_path = self._names_sidecar_path()
628
673
  persisted = False
@@ -703,7 +748,7 @@ class SimViewServer:
703
748
  for start in range(0, len(pending), _CATCHUP_CHUNK_SIZE):
704
749
  chunk = pending[start : start + _CATCHUP_CHUNK_SIZE]
705
750
  await websocket.send_text(
706
- json.dumps(
751
+ dumps_json(
707
752
  {
708
753
  "states": [frame for _, frame in chunk],
709
754
  "frameOffset": pending[start][0],
@@ -726,8 +771,9 @@ class SimViewServer:
726
771
  """
727
772
  if self.model_data is None:
728
773
  return
729
- self.model_data["episodes"] = episodes
730
- self._pack_model()
774
+ with self._model_lock:
775
+ self.model_data["episodes"] = episodes
776
+ self._pack_model()
731
777
 
732
778
  async def broadcast_episodes(self, episodes: list[dict]) -> None:
733
779
  """Push updated episode boundaries to every connected /ws/states client.
@@ -736,7 +782,7 @@ class SimViewServer:
736
782
  the model, not a frame, and arrive far more rarely. See the onmessage
737
783
  handler in SimView.js.
738
784
  """
739
- await self._broadcast_text(json.dumps({"episodes": episodes}))
785
+ await self._broadcast_text(dumps_json({"episodes": episodes}))
740
786
 
741
787
  async def _broadcast_text(self, message: str) -> None:
742
788
  """Send one already-serialized message to every connected client.
@@ -767,7 +813,7 @@ class SimViewServer:
767
813
  thread rather than calling it directly.
768
814
  """
769
815
  await self._broadcast_text(
770
- json.dumps({"states": [frame], "frameOffset": frame_index})
816
+ dumps_json({"states": [frame], "frameOffset": frame_index})
771
817
  )
772
818
 
773
819
  def run(
@@ -934,9 +980,10 @@ class ViewerHandle:
934
980
  """Jupyter calls this automatically when the handle is the result of
935
981
  a cell, embedding the viewer inline without the user having to open a
936
982
  separate browser tab."""
937
- src = self.url_for(self.view) if self.view else self.url
983
+ src = html.escape(self.url_for(self.view) if self.view else self.url)
984
+ height = html.escape(str(self.iframe_height))
938
985
  return (
939
- f'<iframe src="{src}" width="100%" height="{self.iframe_height}" '
986
+ f'<iframe src="{src}" width="100%" height="{height}" '
940
987
  f'style="border:none;" allow="fullscreen"></iframe>'
941
988
  )
942
989
 
@@ -23,7 +23,7 @@ import { ColumnarStateStore, LegacyStateStore } from "./components/StateStore.js
23
23
  import { WindowedField } from "./components/WindowedField.js";
24
24
  import { escapeHtml } from "./utils/html.js";
25
25
  import { bytesPerFrame, shouldWindowField } from "./utils/blobWindow.js";
26
- import { shouldFollowLive } from "./utils/liveFollow.js";
26
+ import { shouldFollowLive, unseenLiveStates } from "./utils/liveFollow.js";
27
27
  import { shiftEpisodes } from "./utils/episodes.js";
28
28
  import { parseViewState, parseStartupOptions, safeStaticBase, serializeViewState, toggleMapFromUiState } from "./utils/viewState.js";
29
29
  import { mergeUiDefaults, applyViewerDomDefaults, panelHideCss } from "./utils/viewerDefaults.js";
@@ -56,6 +56,8 @@ export class SimView {
56
56
  // viewer's frame 0 -- a late-joining tab only gets the catch-up window.
57
57
  // null until the first chunk arrives; see shiftEpisodes.
58
58
  this.liveFrameOffset = null;
59
+ // Live mode: absolute index of the next frame this viewer expects.
60
+ this.liveNextIndex = null;
59
61
  // Static demo mode: set from window.__simviewStaticBase (the GitHub
60
62
  // Pages demo index.html) or the `data=` startup hash key; all data
61
63
  // fetches then go to flat static files (model.json, states.json,
@@ -138,6 +140,7 @@ export class SimView {
138
140
  statesReady.catch(() => {}); // surfaced where it's awaited below
139
141
 
140
142
  console.time("fetch_blobs");
143
+ this.deferTerrainPropertyBlobs(model);
141
144
  await this.fetchBlobs(model);
142
145
  console.timeEnd("fetch_blobs");
143
146
 
@@ -260,7 +263,6 @@ export class SimView {
260
263
  // from /blob/{token}/{id} → {staticBase}/blob/{id} so they resolve against
261
264
  // the pre-dumped flat files deployed alongside the demo page.
262
265
  async fetchBlobs(obj) {
263
- const base = this.staticBase;
264
266
  const refs = [];
265
267
  const collect = (node) => {
266
268
  if (!node || typeof node !== 'object') return;
@@ -271,11 +273,7 @@ export class SimView {
271
273
  for (const key of Object.keys(node)) {
272
274
  const val = node[key];
273
275
  if (typeof val === 'string' && val.startsWith('/blob/')) {
274
- // Static mode: /blob/{token}/{id} → {base}/blob/{id}
275
- const url = base
276
- ? `${base}/blob/${val.split("/").pop()}`
277
- : val;
278
- refs.push({ container: node, key, url });
276
+ refs.push({ container: node, key, url: this.blobUrl(val) });
279
277
  } else if (typeof val === 'object') {
280
278
  collect(val);
281
279
  }
@@ -285,19 +283,40 @@ export class SimView {
285
283
 
286
284
  await Promise.all(
287
285
  refs.map(async ({ container, key, url }) => {
288
- const res = await fetch(url);
289
- // Without this check a 404/500 body (an error page) would be
290
- // silently reinterpreted as float32 data, corrupting whatever
291
- // geometry/trajectory referenced this blob.
292
- if (!res.ok) {
293
- throw new Error(`Failed to fetch blob ${url}: ${res.status} ${res.statusText}`);
294
- }
295
- // Little-endian float32 by contract (Python "<f4").
296
- container[key] = new Float32Array(await res.arrayBuffer());
286
+ container[key] = await this.fetchBlob(url);
297
287
  })
298
288
  );
299
289
  }
300
290
 
291
+ // Static mode: /blob/{token}/{id} → {staticBase}/blob/{id}
292
+ blobUrl(ref) {
293
+ return this.staticBase ? `${this.staticBase}/blob/${ref.split("/").pop()}` : ref;
294
+ }
295
+
296
+ async fetchBlob(url) {
297
+ const res = await fetch(url);
298
+ // Without this check a 404/500 body (an error page) would be
299
+ // silently reinterpreted as float32 data, corrupting whatever
300
+ // geometry/trajectory referenced this blob.
301
+ if (!res.ok) {
302
+ throw new Error(`Failed to fetch blob ${url}: ${res.status} ${res.statusText}`);
303
+ }
304
+ // Little-endian float32 by contract (Python "<f4").
305
+ return new Float32Array(await res.arrayBuffer());
306
+ }
307
+
308
+ // Swaps each terrain property layer's blob URL for a loader, so fetchBlobs
309
+ // skips it (it only collects strings) and Terrain fetches the layer the
310
+ // first time it's shown -- one color mode is visible at a time and most
311
+ // sessions never leave "height". See Terrain.loadProperty.
312
+ deferTerrainPropertyBlobs(model) {
313
+ for (const prop of Object.values(model.terrain?.properties || {})) {
314
+ if (typeof prop?.data !== "string" || !prop.data.startsWith("/blob/")) continue;
315
+ const url = this.blobUrl(prop.data);
316
+ prop.data = { load: () => this.fetchBlob(url) };
317
+ }
318
+ }
319
+
301
320
  // Opens the live-streaming WebSocket (see simview.live.LiveViewer): each
302
321
  // message is `{states: [<frame>, ...]}` -- one catch-up message with
303
322
  // every frame buffered so far, then one message per subsequently pushed
@@ -320,13 +339,27 @@ export class SimView {
320
339
  this.applyEpisodes(message.episodes);
321
340
  return;
322
341
  }
323
- const { states, frameOffset } = message;
342
+ const { states } = message;
324
343
  if (!states || states.length === 0) return;
344
+ // Absent on an older server: assume contiguous frames from 0.
345
+ const frameOffset = Number.isInteger(message.frameOffset)
346
+ ? message.frameOffset
347
+ : (this.liveNextIndex ?? 0);
325
348
  if (this.liveFrameOffset === null) {
326
- // Absent on an older server: assume the stream starts at 0.
327
- this.liveFrameOffset = Number.isInteger(frameOffset) ? frameOffset : 0;
349
+ this.liveFrameOffset = frameOffset;
350
+ this.liveNextIndex = frameOffset;
351
+ }
352
+ if (frameOffset > this.liveNextIndex) {
353
+ // Frames dropped under backpressure: accept and play on as if
354
+ // contiguous (a reload replays them from the server's catch-up
355
+ // buffer), so episode
356
+ // markers past the gap sit early by its size.
357
+ console.warn(`Live stream skipped frames ${this.liveNextIndex}-${frameOffset - 1}.`);
328
358
  }
329
- this.processStatesChunk(states);
359
+ const unseen = unseenLiveStates(states, frameOffset, this.liveNextIndex);
360
+ if (unseen.length === 0) return;
361
+ this.liveNextIndex = frameOffset + states.length;
362
+ this.processStatesChunk(unseen);
330
363
  if (splash) splash.remove();
331
364
  };
332
365
  socket.onclose = () => {
@@ -408,6 +441,8 @@ export class SimView {
408
441
  if (this.terrainProfile) {
409
442
  this.terrainProfile.onStatesAppended();
410
443
  }
444
+ // A live run that started on a single frame gains its trajectory here.
445
+ this.maybeAttachTrajectoryPanels();
411
446
  if (wasFollowingLive) {
412
447
  this.animationController.goToTime(this.store.lastTime());
413
448
  }
@@ -440,7 +475,7 @@ export class SimView {
440
475
  }
441
476
 
442
477
  // The Error Metrics and Terrain tabs need a body with an actual trajectory to sample
443
- // terrain along (a static point cloud with no states doesn't count),
478
+ // terrain along (a body with no states, or only one frame, doesn't count),
444
479
  // which is only known once appendBodyHistories() has filled each body's
445
480
  // validStates. Error Metrics compares batches over time, so it needs the
446
481
  // same plus at least two batches; a static scene gets neither tab.
@@ -72,6 +72,7 @@ export class AnimationController {
72
72
  // Content seconds played since recording started; the recording stops
73
73
  // once this reaches totalTime (one loop), whatever the playback speed.
74
74
  this._recordedSeconds = 0;
75
+ this._capturedFrames = 0; // captureFrame() calls since recording started
75
76
  this.simulationTimestep = simulationTimestep; // Simulation timestep
76
77
  this.lastUpdateTime = null;
77
78
 
@@ -253,6 +254,7 @@ export class AnimationController {
253
254
  this.isRecording = true;
254
255
  this.startTime = performance.now();
255
256
  this._recordedSeconds = 0;
257
+ this._capturedFrames = 0;
256
258
  if (!this.isPlaying) {
257
259
  this.play();
258
260
  }
@@ -397,8 +399,11 @@ export class AnimationController {
397
399
  // here -- the browser samples the canvas on its own timer.
398
400
 
399
401
  // Stop recording once one loop of content has played (content
400
- // seconds, not wall-clock, so 2x doesn't record two loops).
401
- if (this._recordedSeconds >= this.totalTime) {
402
+ // seconds, not wall-clock, so 2x doesn't record two loops). Never on
403
+ // the first captured tick: a single-frame scene (totalTime 0) would
404
+ // stop before its frame landed, leaving an empty video.
405
+ this._capturedFrames++;
406
+ if (this._capturedFrames > 1 && this._recordedSeconds >= this.totalTime) {
402
407
  this.playbackControls.recordButton.click();
403
408
  }
404
409
  }
@@ -8,6 +8,11 @@ import {
8
8
  windowsToPrefetch,
9
9
  } from "../utils/blobWindow.js";
10
10
 
11
+ // A failed window isn't refetched for this long: rowsAt runs every frame, so
12
+ // without it a dead URL (e.g. a blob token invalidated by a server restart)
13
+ // would be hit ~60 times a second.
14
+ export const RETRY_BACKOFF_MS = 5000;
15
+
11
16
  // One columnar field fetched in windows around the playhead instead of whole,
12
17
  // for long trajectories where the full (T, B, k) blob would be hundreds of
13
18
  // megabytes. See utils/blobWindow.js for which fields qualify and why, and
@@ -39,6 +44,8 @@ export class WindowedField {
39
44
  this._windows = new Map();
40
45
  // windowIndex -> in-flight promise, so a window is only fetched once.
41
46
  this._pending = new Map();
47
+ // windowIndex -> Date.now() of its last failed fetch (see RETRY_BACKOFF_MS).
48
+ this._failedAt = new Map();
42
49
  // windowIndex list, least recently used first.
43
50
  this._accessOrder = [];
44
51
  this.fetchCount = 0;
@@ -97,6 +104,9 @@ export class WindowedField {
97
104
  this.bytesPerFrame
98
105
  );
99
106
  if (!range) return Promise.resolve();
107
+ if (Date.now() - (this._failedAt.get(windowIndex) ?? -Infinity) < RETRY_BACKOFF_MS) {
108
+ return Promise.resolve();
109
+ }
100
110
 
101
111
  this.fetchCount++;
102
112
  const promise = this._fetch(this.url, {
@@ -123,6 +133,7 @@ export class WindowedField {
123
133
  })
124
134
  .then((buffer) => {
125
135
  this._windows.set(windowIndex, new Float32Array(buffer)); // little-endian "<f4"
136
+ this._failedAt.delete(windowIndex);
126
137
  this._touch(windowIndex);
127
138
  this._evict();
128
139
  if (this.onLanded) this.onLanded();
@@ -132,6 +143,7 @@ export class WindowedField {
132
143
  // failed window degrades to "no arrow" rather than a broken
133
144
  // viewer. Logged so it isn't silent.
134
145
  console.error(error);
146
+ this._failedAt.set(windowIndex, Date.now());
135
147
  })
136
148
  .finally(() => {
137
149
  this._pending.delete(windowIndex);