hstream-3d 0.1.0__py3-none-any.whl

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.
hstream_3d/__init__.py ADDED
@@ -0,0 +1,491 @@
1
+ """3D model viewers for HStream: Google's ``<model-viewer>`` and Babylon.js
2
+ Viewer v2 (``<babylon-viewer>``), as ``viewer3d.*``.
3
+
4
+ ::
5
+
6
+ from hstream import hs, viewer3d
7
+ from hstream_3d import Annotation
8
+
9
+ pick = viewer3d.model_viewer("https://modelviewer.dev/shared-assets/models/Astronaut.glb")
10
+ if pick:
11
+ hs.markdown(f"You clicked {pick.point}")
12
+
13
+ Clicking the model posts the 3D hit to the server; the viewer returns it as
14
+ a :class:`Pick` (``None`` until the first click). ``annotations=`` pins labels
15
+ onto the model. Each viewer loads from a CDN, only on pages that use it.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import base64
21
+ import hashlib
22
+ import json
23
+ import os
24
+ from dataclasses import dataclass, field
25
+ from importlib.resources import files
26
+ from pathlib import Path
27
+ from typing import Any, Iterable, Optional, Sequence, Tuple, Union
28
+ from urllib.parse import quote
29
+
30
+ from hstream import ComponentNamespace, component_wrapper, register_namespace
31
+ from hstream.context import current_tree
32
+
33
+ MODEL_VIEWER_VERSION = "4.4.0"
34
+ BABYLON_VIEWER_VERSION = "9.38.1"
35
+
36
+ MODEL_VIEWER_JS = (
37
+ "https://cdn.jsdelivr.net/npm/@google/model-viewer@"
38
+ f"{MODEL_VIEWER_VERSION}/dist/model-viewer.min.js"
39
+ )
40
+ BABYLON_VIEWER_JS = (
41
+ "https://cdn.jsdelivr.net/npm/@babylonjs/viewer@"
42
+ f"{BABYLON_VIEWER_VERSION}/dist/babylon-viewer.esm.min.js"
43
+ )
44
+
45
+ _PICK_JS = "\n".join(
46
+ line
47
+ for line in files("hstream_3d").joinpath("pick.js").read_text().splitlines()
48
+ if line.strip() and not line.strip().startswith("//")
49
+ )
50
+
51
+ # Viewers have no size of their own; annotations are a dot with a label.
52
+ _CSS = """<style>
53
+ model-viewer[hs-viewer], babylon-viewer[hs-viewer] {
54
+ display: block; width: 100%; margin-block-end: var(--pico-spacing, 1rem);
55
+ border-radius: var(--pico-border-radius, 0.25rem);
56
+ }
57
+ .hs-annotation {
58
+ all: unset; display: block; box-sizing: border-box; position: relative;
59
+ width: 14px; height: 14px; border-radius: 50%; cursor: default;
60
+ background: var(--pico-primary, #1095c1); border: 2px solid #fff;
61
+ box-shadow: 0 1px 4px rgba(0, 0, 0, 0.4);
62
+ }
63
+ .hs-annotation > span {
64
+ position: absolute; left: 18px; top: 50%; transform: translateY(-50%);
65
+ white-space: nowrap; padding: 1px 8px; border-radius: 4px;
66
+ background: rgba(0, 0, 0, 0.75); color: #fff; font-size: 0.8rem;
67
+ }
68
+ .hs-annotation > span:empty { display: none; }
69
+ model-viewer .hs-annotation:not([data-visible]) { opacity: 0.35; }
70
+ </style>"""
71
+
72
+ Vec3 = Tuple[float, float, float]
73
+
74
+
75
+ @dataclass(frozen=True)
76
+ class Pick:
77
+ """Where a click hit the model.
78
+
79
+ ``point`` and ``normal`` are in the viewer's coordinates (model space for
80
+ ``<model-viewer>``, world space for Babylon), so they can be passed
81
+ straight back as an :class:`Annotation`. ``screen`` is the click in pixels
82
+ from the viewer's top-left corner.
83
+ """
84
+
85
+ point: Vec3
86
+ normal: Optional[Vec3] = None
87
+ screen: Optional[Tuple[float, float]] = None
88
+ #: Babylon: the mesh's name. (<model-viewer> doesn't report meshes.)
89
+ mesh: Optional[str] = None
90
+ material: Optional[str] = None
91
+ #: Babylon: the triangle index in the mesh.
92
+ face: Optional[int] = None
93
+ uv: Optional[Tuple[float, float]] = None
94
+ #: A reference that follows an animated mesh: a ``data-surface`` string
95
+ #: for <model-viewer>, a "surface" hotspot dict for Babylon (sent only for
96
+ #: skinned/morphing meshes). Babylon pins use it automatically;
97
+ #: <model-viewer> only via ``Annotation(pick, surface=pick.surface)``.
98
+ surface: Any = None
99
+ viewer: Optional[str] = None
100
+ raw: dict = field(default_factory=dict, compare=False, repr=False)
101
+
102
+ @classmethod
103
+ def parse(cls, value: Any) -> Optional["Pick"]:
104
+ """A ``Pick`` from the posted JSON (or a dict), else ``None``."""
105
+ if isinstance(value, Pick):
106
+ return value
107
+ if isinstance(value, str):
108
+ if not value.strip():
109
+ return None
110
+ try:
111
+ value = json.loads(value)
112
+ except ValueError:
113
+ return None
114
+ if not isinstance(value, dict):
115
+ return None
116
+ point = _vec(value.get("point"), 3)
117
+ if point is None:
118
+ return None
119
+ face = value.get("face")
120
+ return cls(
121
+ point=point,
122
+ normal=_vec(value.get("normal"), 3),
123
+ screen=_vec(value.get("screen"), 2),
124
+ mesh=value.get("mesh"),
125
+ material=value.get("material"),
126
+ face=face if isinstance(face, int) else None,
127
+ uv=_vec(value.get("uv"), 2),
128
+ surface=value.get("surface"),
129
+ viewer=value.get("viewer"),
130
+ raw=value,
131
+ )
132
+
133
+
134
+ @dataclass(frozen=True)
135
+ class Annotation:
136
+ """A label pinned to a point on the model.
137
+
138
+ ``Annotation((0, 1.2, 0), "Head")``, or from a click:
139
+ ``Annotation(pick, "Here")`` (uses the pick's point, normal and surface).
140
+ """
141
+
142
+ point: Union[Vec3, Pick]
143
+ label: str = ""
144
+ normal: Optional[Vec3] = None
145
+ #: Pin to a surface that moves with the mesh. From a Babylon pick this is
146
+ #: used automatically; a <model-viewer> surface id only when passed here.
147
+ surface: Any = None
148
+
149
+ @property
150
+ def explicit_surface(self) -> bool:
151
+ return getattr(self, "_explicit_surface", self.surface is not None)
152
+
153
+ def resolved(self) -> "Annotation":
154
+ if not isinstance(self.point, Pick):
155
+ return self
156
+ pick = self.point
157
+ note = Annotation(
158
+ pick.point,
159
+ self.label,
160
+ self.normal or pick.normal,
161
+ self.surface if self.surface is not None else pick.surface,
162
+ )
163
+ object.__setattr__(note, "_explicit_surface", self.surface is not None)
164
+ return note
165
+
166
+
167
+ def _vec(value: Any, size: int) -> Optional[tuple]:
168
+ if not isinstance(value, (list, tuple)) or len(value) != size:
169
+ return None
170
+ try:
171
+ return tuple(float(v) for v in value)
172
+ except (TypeError, ValueError):
173
+ return None
174
+
175
+
176
+ def _annotations(items: Optional[Iterable[Any]]) -> list:
177
+ result = []
178
+ for item in items or ():
179
+ if isinstance(item, Annotation):
180
+ result.append(item.resolved())
181
+ elif isinstance(item, Pick):
182
+ result.append(Annotation(item).resolved())
183
+ elif isinstance(item, dict):
184
+ result.append(
185
+ Annotation(
186
+ tuple(item["point"]),
187
+ item.get("label", ""),
188
+ item.get("normal"),
189
+ item.get("surface"),
190
+ )
191
+ )
192
+ elif (
193
+ len(item) == 2
194
+ and isinstance(item[1], str)
195
+ and isinstance(item[0], (list, tuple, Pick))
196
+ ): # (point_or_pick, label)
197
+ point = item[0] if isinstance(item[0], Pick) else tuple(item[0])
198
+ result.append(Annotation(point, item[1]).resolved())
199
+ else: # a bare (x, y, z)
200
+ result.append(Annotation(tuple(item)))
201
+ return result
202
+
203
+
204
+ def _notes(annotations, show_pick, stored) -> list:
205
+ """The annotations to render, plus the latest pick when ``show_pick``."""
206
+ notes = _annotations(annotations)
207
+ pick = Pick.parse(stored)
208
+ if show_pick and pick is not None:
209
+ label = show_pick if isinstance(show_pick, str) else ""
210
+ notes.append(Annotation(pick, label).resolved())
211
+ return notes
212
+
213
+
214
+ _MIME = {".glb": "model/gltf-binary", ".gltf": "model/gltf+json"}
215
+ _data_urls: dict = {}
216
+
217
+
218
+ def model_url(src: Union[str, os.PathLike]) -> Tuple[str, Optional[str]]:
219
+ """``(url, extension)`` for a viewer's ``src``.
220
+
221
+ URLs pass through. A local file (a ``Path``, or a string that is an
222
+ existing path) becomes a ``data:`` URL, since HStream serves no files:
223
+ fine for models up to a few MB, sent with each page update. Use a
224
+ self-contained ``.glb``; a ``.gltf`` with separate buffer files won't
225
+ load. ``extension`` tells Babylon the format (a data URL has no name).
226
+ """
227
+ if not isinstance(src, os.PathLike):
228
+ text = str(src)
229
+ if (
230
+ "://" in text
231
+ or text.startswith(("data:", "blob:"))
232
+ or not os.path.isfile(text)
233
+ ):
234
+ return text, None # a URL (absolute or relative to the page)
235
+ path = Path(src)
236
+ if not path.is_file():
237
+ return os.fspath(src), None
238
+ stat = path.stat()
239
+ cache_key = (str(path.resolve()), stat.st_mtime_ns, stat.st_size)
240
+ url = _data_urls.pop(cache_key, None)
241
+ if url is None:
242
+ mime = _MIME.get(path.suffix.lower(), "application/octet-stream")
243
+ url = f"data:{mime};base64," + base64.b64encode(path.read_bytes()).decode(
244
+ "ascii"
245
+ )
246
+ _data_urls[cache_key] = url # most recently used last
247
+ while len(_data_urls) > 8:
248
+ _data_urls.pop(next(iter(_data_urls)))
249
+ return url, path.suffix.lower() or None
250
+
251
+
252
+ def _pin_id(i: int, note: "Annotation") -> str:
253
+ """A name for pin ``i`` that changes when the pin moves.
254
+
255
+ Neither viewer re-reads a hotspot whose position attribute changes in
256
+ place, so a moved pin must arrive as a new element (the morph removes the
257
+ old one and inserts this), which the viewer picks up as a new hotspot.
258
+ """
259
+ where = repr((note.point, note.normal, note.surface)).encode()
260
+ return f"{i}-{hashlib.sha1(where).hexdigest()[:8]}"
261
+
262
+
263
+ def _attr_name(name: str) -> str:
264
+ if name in ("klass", "class_"):
265
+ return "class"
266
+ return name.rstrip("_").replace("_", "-")
267
+
268
+
269
+ def _attrs(values: dict) -> list:
270
+ """Attribute tuples: ``True`` -> present, ``False``/``None`` -> absent."""
271
+ pairs = []
272
+ for name, value in values.items():
273
+ if value is None or value is False:
274
+ continue
275
+ pairs.append((name, "" if value is True else str(value)))
276
+ return pairs
277
+
278
+
279
+ def _num(value: float) -> str:
280
+ return f"{value:g}"
281
+
282
+
283
+ class Viewer3D(ComponentNamespace):
284
+ """``viewer3d``: 3D model viewers whose clicks come back as a :class:`Pick`."""
285
+
286
+ Pick = Pick
287
+ Annotation = Annotation
288
+
289
+ def _setup(self, script_url: str) -> None:
290
+ tree = current_tree()
291
+ tree.add_asset(f'<script type="module" src="{script_url}"></script>')
292
+ tree.add_asset(f"<script>{_PICK_JS}</script>")
293
+ tree.add_asset(_CSS)
294
+
295
+ def _viewer_attrs(self, key, pickable, height, named, extra) -> list:
296
+ url = f"/set_component_value?component_id={quote(str(key))}"
297
+ style = f"height: {height}"
298
+ if extra.get("style"):
299
+ style = f"{style}; {extra.pop('style')}"
300
+ pairs = [("hs-viewer", "")]
301
+ if pickable:
302
+ pairs += [
303
+ ("hs-pick", ""),
304
+ ("hx-post", url),
305
+ ("hx-trigger", "hs-pick"),
306
+ ("hx-vals", "js:{new_value: JSON.stringify(ctx.sourceEvent.detail)}"),
307
+ ]
308
+ pairs.append(("style", style))
309
+ pairs += _attrs(named)
310
+ pairs += _attrs({_attr_name(k): v for k, v in extra.items()})
311
+ return pairs
312
+
313
+ @component_wrapper(tag="model-viewer")
314
+ def model_viewer(
315
+ self,
316
+ src: Union[str, os.PathLike],
317
+ *,
318
+ key: Optional[str] = None,
319
+ annotations: Optional[Sequence[Any]] = None,
320
+ show_pick: Union[bool, str] = False,
321
+ pickable: bool = True,
322
+ height: str = "400px",
323
+ alt: str = "3D model",
324
+ camera_controls: bool = True,
325
+ auto_rotate: Optional[bool] = None,
326
+ autoplay: Optional[bool] = None,
327
+ animation_name: Optional[str] = None,
328
+ ar: Optional[bool] = None,
329
+ poster: Optional[str] = None,
330
+ environment_image: Optional[str] = None,
331
+ skybox_image: Optional[str] = None,
332
+ exposure: Optional[float] = None,
333
+ shadow_intensity: Optional[float] = None,
334
+ camera_orbit: Optional[str] = None,
335
+ camera_target: Optional[str] = None,
336
+ field_of_view: Optional[str] = None,
337
+ touch_action: str = "pan-y",
338
+ **attrs: Any,
339
+ ) -> Optional[Pick]:
340
+ """Google's ``<model-viewer>`` (glTF/GLB): https://modelviewer.dev
341
+
342
+ ``src`` is a URL or a local ``.glb`` file (see :func:`model_url`).
343
+
344
+ Returns the last :class:`Pick` (where the user clicked the model), or
345
+ ``None``. ``annotations`` pins labels: a list of :class:`Annotation`,
346
+ picks, or ``(x, y, z)`` points in model space; ``show_pick=True`` (or a label string) pins
347
+ the latest click. Any other
348
+ ``<model-viewer>`` attribute is a keyword argument (``ar_modes=...``,
349
+ ``interaction_prompt="none"``); see https://modelviewer.dev/docs/.
350
+ """
351
+ self._setup(MODEL_VIEWER_JS)
352
+ notes = _notes(annotations, show_pick, attrs.pop("value", None))
353
+ named = {
354
+ "src": model_url(src)[0],
355
+ "alt": alt,
356
+ "camera-controls": camera_controls,
357
+ "auto-rotate": auto_rotate,
358
+ "autoplay": autoplay,
359
+ "animation-name": animation_name,
360
+ "ar": ar,
361
+ "poster": poster,
362
+ "environment-image": environment_image,
363
+ "skybox-image": skybox_image,
364
+ "exposure": exposure,
365
+ "shadow-intensity": shadow_intensity,
366
+ "camera-orbit": camera_orbit,
367
+ "camera-target": camera_target,
368
+ "field-of-view": field_of_view,
369
+ "touch-action": touch_action,
370
+ # A click picks, so it mustn't also recentre the camera on the
371
+ # clicked point (model-viewer's default), which drags every new
372
+ # pin to the middle of the view.
373
+ "disable-tap": bool(pickable and camera_controls),
374
+ }
375
+ tree = current_tree()
376
+ tree.attr(*self._viewer_attrs(key, pickable, height, named, attrs))
377
+ for i, note in enumerate(notes):
378
+ normal = note.normal or (0.0, 1.0, 0.0)
379
+ pairs = [
380
+ ("id", f"{key}_annotation_{_pin_id(i, note)}"),
381
+ ("slot", f"hotspot-{_pin_id(i, note)}"),
382
+ ("class", "hs-annotation"),
383
+ ("type", "button"),
384
+ ]
385
+ # data-position (model space, exactly where the pick hit). A
386
+ # model-viewer surface id (data-surface) is only for animated
387
+ # models and is opt-in: Annotation(..., surface=pick.surface).
388
+ pairs += [
389
+ ("data-position", " ".join(f"{_num(v)}m" for v in note.point)),
390
+ ("data-normal", " ".join(f"{_num(v)}m" for v in normal)),
391
+ ]
392
+ if isinstance(note.surface, str) and note.explicit_surface:
393
+ pairs.append(("data-surface", note.surface))
394
+ with tree.tag("button", *pairs):
395
+ with tree.tag("span"):
396
+ tree.text(note.label)
397
+ return Pick.parse
398
+
399
+ @component_wrapper(tag="babylon-viewer")
400
+ def babylon(
401
+ self,
402
+ source: Union[str, os.PathLike],
403
+ *,
404
+ key: Optional[str] = None,
405
+ annotations: Optional[Sequence[Any]] = None,
406
+ show_pick: Union[bool, str] = False,
407
+ pickable: bool = True,
408
+ height: str = "400px",
409
+ environment: Optional[str] = None,
410
+ environment_lighting: Optional[str] = None,
411
+ environment_skybox: Optional[str] = None,
412
+ environment_intensity: Optional[float] = None,
413
+ skybox_blur: Optional[float] = None,
414
+ tone_mapping: Optional[str] = None,
415
+ shadow_quality: Optional[str] = None,
416
+ clear_color: Optional[str] = None,
417
+ camera_auto_orbit: Optional[bool] = None,
418
+ animation_auto_play: Optional[bool] = None,
419
+ selected_animation: Optional[int] = None,
420
+ **attrs: Any,
421
+ ) -> Optional[Pick]:
422
+ """Babylon.js Viewer v2 (``<babylon-viewer>``): https://doc.babylonjs.com/toolsAndResources/viewerV2
423
+
424
+ ``source`` is a URL or a local ``.glb`` file (see :func:`model_url`).
425
+
426
+ Returns the last :class:`Pick` (Babylon's ``pickInfo``: world-space
427
+ point and normal, mesh name, face index, uv, screen position), or
428
+ ``None``. ``annotations`` pins labels (world space); an annotation made
429
+ from a pick follows the mesh surface as it animates; ``show_pick=True`` (or a label string) pins
430
+ the latest click. Other
431
+ ``<babylon-viewer>`` attributes are keyword arguments.
432
+ """
433
+ self._setup(BABYLON_VIEWER_JS)
434
+ notes = _notes(annotations, show_pick, attrs.pop("value", None))
435
+ hotspots = {}
436
+ for i, note in enumerate(notes):
437
+ if (
438
+ isinstance(note.surface, dict)
439
+ and note.surface.get("meshIndex", -1) >= 0
440
+ ):
441
+ hotspots[f"hs{_pin_id(i, note)}"] = {**note.surface, "type": "surface"}
442
+ else:
443
+ hotspots[f"hs{_pin_id(i, note)}"] = {
444
+ "type": "world",
445
+ "position": list(note.point),
446
+ "normal": list(note.normal or (0.0, 1.0, 0.0)),
447
+ }
448
+ source_url, extension = model_url(source)
449
+ named = {
450
+ "source": source_url,
451
+ "extension": extension if source_url.startswith("data:") else None,
452
+ "environment": environment,
453
+ "environment-lighting": environment_lighting,
454
+ "environment-skybox": environment_skybox,
455
+ "environment-intensity": environment_intensity,
456
+ "skybox-blur": skybox_blur,
457
+ "tone-mapping": tone_mapping,
458
+ "shadow-quality": shadow_quality,
459
+ "clear-color": clear_color,
460
+ "camera-auto-orbit": camera_auto_orbit,
461
+ "animation-auto-play": animation_auto_play,
462
+ "selected-animation": selected_animation,
463
+ "hotspots": json.dumps(hotspots, separators=(",", ":"))
464
+ if hotspots
465
+ else None,
466
+ }
467
+ tree = current_tree()
468
+ tree.attr(*self._viewer_attrs(key, pickable, height, named, attrs))
469
+ for i, note in enumerate(notes):
470
+ with tree.tag(
471
+ "babylon-viewer-annotation",
472
+ ("id", f"{key}_annotation_{_pin_id(i, note)}"),
473
+ ("hotspot", f"hs{_pin_id(i, note)}"),
474
+ ):
475
+ with tree.tag("div", ("class", "hs-annotation")):
476
+ with tree.tag("span"):
477
+ tree.text(note.label)
478
+ return Pick.parse
479
+
480
+
481
+ viewer3d = register_namespace("viewer3d", Viewer3D())
482
+
483
+ __all__ = [
484
+ "viewer3d",
485
+ "Viewer3D",
486
+ "Pick",
487
+ "Annotation",
488
+ "model_url",
489
+ "MODEL_VIEWER_VERSION",
490
+ "BABYLON_VIEWER_VERSION",
491
+ ]
hstream_3d/pick.js ADDED
@@ -0,0 +1,107 @@
1
+ // hstream-3d: turn a click/tap on a 3D viewer into an `hs-pick` event.
2
+ //
3
+ // A viewer rendered with pickable=True carries the `hs-pick` attribute and
4
+ // `hx-trigger="hs-pick"`; htmx posts JSON.stringify(event.detail) as its new
5
+ // value. Drags (orbiting the camera) and clicks that miss the model send
6
+ // nothing, and neither does a click on an annotation.
7
+ (function () {
8
+ if (window.hsPick3d) return;
9
+ window.hsPick3d = true;
10
+
11
+ function send(elt, detail) {
12
+ elt.dispatchEvent(new CustomEvent('hs-pick', { detail: detail }));
13
+ }
14
+
15
+ function round(v) { return Math.round(v * 1e5) / 1e5; }
16
+ function vec3(v) { return v ? [round(v.x), round(v.y), round(v.z)] : null; }
17
+ function screen(elt, clientX, clientY) {
18
+ var r = elt.getBoundingClientRect();
19
+ return [Math.round(clientX - r.left), Math.round(clientY - r.top)];
20
+ }
21
+
22
+ // <model-viewer>: positionAndNormalFromPoint on a click that wasn't a drag.
23
+ var down = null;
24
+ document.addEventListener('pointerdown', function (e) {
25
+ down = [e.clientX, e.clientY];
26
+ }, true);
27
+ document.addEventListener('click', function (e) {
28
+ var mv = e.target.closest && e.target.closest('model-viewer[hs-pick]');
29
+ if (!mv || e.target.closest('[slot^="hotspot"]')) return;
30
+ if (down && Math.hypot(e.clientX - down[0], e.clientY - down[1]) > 5) return;
31
+ var hit = mv.positionAndNormalFromPoint(e.clientX, e.clientY);
32
+ if (!hit) return;
33
+ var material = mv.materialFromPoint && mv.materialFromPoint(e.clientX, e.clientY);
34
+ send(mv, {
35
+ viewer: 'model-viewer',
36
+ point: vec3(hit.position),
37
+ normal: vec3(hit.normal),
38
+ uv: hit.uv ? [round(hit.uv.u), round(hit.uv.v)] : null,
39
+ material: material ? material.name : null,
40
+ surface: mv.surfaceFromPoint(e.clientX, e.clientY),
41
+ screen: screen(mv, e.clientX, e.clientY)
42
+ });
43
+ });
44
+
45
+ // <babylon-viewer>: the scene's POINTERTAP (a click/tap, not an orbit drag).
46
+ var POINTERTAP = 0x20;
47
+
48
+ function hookBabylon(elt) {
49
+ var details;
50
+ try { details = elt.viewerDetails; } catch (err) { return; }
51
+ if (!details || !details.scene || details.scene.hsPick) return;
52
+ details.scene.hsPick = true;
53
+ var scene = details.scene;
54
+ scene.onPointerObservable.add(function (info) {
55
+ if (info.type !== POINTERTAP || !elt.hasAttribute('hs-pick')) return;
56
+ // The viewer skips picking on pointer events (and leaves Ray out of its
57
+ // bundle); viewerDetails.pick loads it and refreshes animated meshes.
58
+ var event = info.event || {};
59
+ elt.viewerDetails.pick(scene.pointerX, scene.pointerY).then(function (pick) {
60
+ if (!pick || !pick.hit || !pick.pickedPoint) return;
61
+ sendBabylonPick(elt, pick, event);
62
+ });
63
+ });
64
+ }
65
+
66
+ function sendBabylonPick(elt, pick, event) {
67
+ var mesh = pick.pickedMesh;
68
+ var model = elt.viewerDetails.model;
69
+ var surface = null;
70
+ // A static mesh gets an exact world-space pin (point + normal). Only an
71
+ // animated one (skinned or morphing) needs a surface reference to follow.
72
+ var animated = mesh && (mesh.skeleton || mesh.morphTargetManager);
73
+ if (animated && model && pick.faceId >= 0 && mesh.getIndices) {
74
+ var indices = mesh.getIndices();
75
+ var i = pick.faceId * 3;
76
+ if (indices && indices.length > i + 2) {
77
+ surface = {
78
+ type: 'surface',
79
+ meshIndex: model.assetContainer.meshes.indexOf(mesh),
80
+ pointIndex: [indices[i], indices[i + 1], indices[i + 2]],
81
+ // Babylon weights the triangle's corners (bu, bv, 1 - bu - bv).
82
+ barycentric: [round(pick.bu), round(pick.bv), round(1 - pick.bu - pick.bv)]
83
+ };
84
+ }
85
+ }
86
+ var uv = pick.getTextureCoordinates && pick.getTextureCoordinates();
87
+ send(elt, {
88
+ viewer: 'babylon',
89
+ point: vec3(pick.pickedPoint),
90
+ normal: vec3(pick.getNormal(true)),
91
+ uv: uv ? [round(uv.x), round(uv.y)] : null,
92
+ mesh: mesh ? mesh.name : null,
93
+ material: mesh && mesh.material ? mesh.material.name : null,
94
+ face: pick.faceId,
95
+ surface: surface,
96
+ screen: screen(elt, event.clientX || 0, event.clientY || 0)
97
+ });
98
+ }
99
+
100
+ function hookAll() {
101
+ document.querySelectorAll('babylon-viewer').forEach(hookBabylon);
102
+ }
103
+ // viewerready doesn't need to bubble: the capture phase still passes here.
104
+ document.addEventListener('viewerready', function (e) { hookBabylon(e.target); }, true);
105
+ document.addEventListener('htmx:after:swap', hookAll);
106
+ hookAll();
107
+ })();
@@ -0,0 +1,90 @@
1
+ Metadata-Version: 2.5
2
+ Name: hstream-3d
3
+ Version: 0.1.0
4
+ Summary: 3D model viewers for HStream apps (Google <model-viewer> and Babylon.js Viewer v2), with click picking and annotations.
5
+ Project-URL: Repository, https://github.com/conradbez/hstream
6
+ Requires-Python: >=3.10
7
+ Requires-Dist: hstream>=0.9.0
8
+ Description-Content-Type: text/markdown
9
+
10
+ # hstream-3d
11
+
12
+ 3D model viewers for [HStream](../README.md) apps, as `viewer3d.*`:
13
+ Google's [`<model-viewer>`](https://modelviewer.dev) and
14
+ [Babylon.js Viewer v2](https://doc.babylonjs.com/toolsAndResources/viewerV2).
15
+ Click the model and your script gets the 3D point that was hit.
16
+
17
+ ```bash
18
+ pip install "hstream[3d]"
19
+ ```
20
+
21
+ ```python
22
+ from hstream import hs, viewer3d
23
+
24
+ pick = viewer3d.model_viewer(
25
+ "https://modelviewer.dev/shared-assets/models/Astronaut.glb",
26
+ show_pick="You clicked here",
27
+ )
28
+ if pick:
29
+ hs.markdown(f"point {pick.point}, normal {pick.normal}")
30
+ ```
31
+
32
+ `viewer3d.babylon(source, ...)` works the same way. Each viewer's script
33
+ loads from its CDN, only on pages that use it.
34
+
35
+ ## Picking
36
+
37
+ A click (not an orbit drag) posts the hit; the viewer returns a `Pick`, or
38
+ `None` before the first click:
39
+
40
+ | Field | `model_viewer` | `babylon` |
41
+ | :--- | :--- | :--- |
42
+ | `point`, `normal` | model space | world space |
43
+ | `screen` | pixels from the viewer's top-left | same |
44
+ | `material` | material name | material name |
45
+ | `mesh`, `face` | not reported | mesh name, triangle index |
46
+ | `uv` | texture coordinates | texture coordinates |
47
+ | `surface` | `data-surface` id | surface hotspot (animated meshes only) |
48
+
49
+ Coordinates are glTF units (meters). A CAD model's "faces" are not glTF
50
+ triangles: `face` is the triangle, so map back to CAD faces yourself (for
51
+ example by material or mesh name).
52
+
53
+ ## Annotations
54
+
55
+ ```python
56
+ from hstream_3d import Annotation
57
+
58
+ viewer3d.babylon(
59
+ url,
60
+ annotations=[
61
+ ((0, 1.2, 0), "Head"), # (point, label)
62
+ Annotation(pick, "Picked"), # from a click
63
+ ],
64
+ )
65
+ ```
66
+
67
+ `show_pick=True` (or a label) pins the latest click. Pins are the viewers'
68
+ own hotspots, so they stay on the model as it rotates.
69
+
70
+ ## Local files
71
+
72
+ `src`/`source` can be a local `.glb` (a `Path`, or a path string that
73
+ exists). HStream serves no files, so it is sent inline as a `data:` URL:
74
+ fine up to a few MB. Use self-contained `.glb`, not `.gltf` with separate
75
+ buffers. A changed file is picked up on the next rerun.
76
+
77
+ [`examples/build123d_part.py`](examples/build123d_part.py) builds a
78
+ parametric part with [build123d](https://github.com/gumyr/build123d) on every
79
+ input change, saves each build to `examples/models/`, and falls back to the
80
+ last saved model when build123d isn't installed or a build fails.
81
+
82
+ ## Over plain HTTP (agents, curl)
83
+
84
+ `POST /set_component_value?component_id=<key>` with `new_value` set to
85
+ JSON: `{"point": [x, y, z], "normal": [x, y, z]}` (other fields optional).
86
+
87
+ ## Examples
88
+
89
+ - `hstream run examples/pick_demo.py`: both viewers, click to pin a label.
90
+ - `hstream run examples/build123d_part.py`: parametric CAD part.
@@ -0,0 +1,6 @@
1
+ hstream_3d/__init__.py,sha256=-Au6Os1rn5crt_T0EoMHUuvgo0rfnBejwGJb0Nu2c0g,18461
2
+ hstream_3d/pick.js,sha256=Gr0Rb0RZm7nAwj56yevM6TMaEF30UqGzgENA3AZFePo,4447
3
+ hstream_3d-0.1.0.dist-info/METADATA,sha256=djAUcjlw9mbWnTNJ7A6PMEcEqJLVu2gpy3Q0fY-0Wi0,3006
4
+ hstream_3d-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
5
+ hstream_3d-0.1.0.dist-info/entry_points.txt,sha256=iMrwPhUE3-39KrEh-WdzRXzxY8oe2WFzawWwQ_5W2Dw,43
6
+ hstream_3d-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [hstream.components]
2
+ viewer3d = hstream_3d