trame-vtkjs 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.
Files changed (54) hide show
  1. trame/__init__.py +1 -0
  2. trame/modules/__init__.py +1 -0
  3. trame/modules/vtkjs.py +1 -0
  4. trame/widgets/__init__.py +1 -0
  5. trame/widgets/vtkjs.py +9 -0
  6. trame_vtkjs/__init__.py +39 -0
  7. trame_vtkjs/host_types.py +43 -0
  8. trame_vtkjs/interaction.py +122 -0
  9. trame_vtkjs/module/__init__.py +47 -0
  10. trame_vtkjs/module/array_datatypes.py +98 -0
  11. trame_vtkjs/module/coincident_topology.py +40 -0
  12. trame_vtkjs/module/feature_blocks.py +89 -0
  13. trame_vtkjs/module/node_arrays.py +338 -0
  14. trame_vtkjs/module/node_translator.py +400 -0
  15. trame_vtkjs/module/point_cloud_presentation.py +44 -0
  16. trame_vtkjs/module/point_gaussian.py +30 -0
  17. trame_vtkjs/module/protocol.py +60 -0
  18. trame_vtkjs/module/push_views.py +135 -0
  19. trame_vtkjs/module/serve/js/build-info.json +31 -0
  20. trame_vtkjs/module/serve/js/tiles3dDecodeWorker.classic.js +13 -0
  21. trame_vtkjs/module/serve/js/trame_vtkjs.umd.js +1112 -0
  22. trame_vtkjs/module/serve/wasm/tiles3d/basis_encoder.js +21 -0
  23. trame_vtkjs/module/serve/wasm/tiles3d/basis_encoder.wasm +0 -0
  24. trame_vtkjs/module/serve/wasm/tiles3d/draco_decoder.wasm +0 -0
  25. trame_vtkjs/module/serve/wasm/tiles3d/draco_wasm_wrapper.js +117 -0
  26. trame_vtkjs/module/state_cache.py +106 -0
  27. trame_vtkjs/module/streamed_scene_translation.py +36 -0
  28. trame_vtkjs/module/validation.py +14 -0
  29. trame_vtkjs/module/vtkjs_translator.py +342 -0
  30. trame_vtkjs/projected_texture.py +121 -0
  31. trame_vtkjs/py.typed +0 -0
  32. trame_vtkjs/screen_size_glyphs.py +61 -0
  33. trame_vtkjs/store.py +511 -0
  34. trame_vtkjs/streamed_scene.py +384 -0
  35. trame_vtkjs/streamed_scene_blocks.py +88 -0
  36. trame_vtkjs/view_types.py +8 -0
  37. trame_vtkjs/widgets/__init__.py +4 -0
  38. trame_vtkjs/widgets/blob_payloads.py +114 -0
  39. trame_vtkjs/widgets/dependency_graph.py +148 -0
  40. trame_vtkjs/widgets/dirty_batch.py +34 -0
  41. trame_vtkjs/widgets/dirty_tracker.py +324 -0
  42. trame_vtkjs/widgets/hot_array_batch.py +83 -0
  43. trame_vtkjs/widgets/hot_arrays.py +348 -0
  44. trame_vtkjs/widgets/publisher.py +494 -0
  45. trame_vtkjs/widgets/scene_events.py +33 -0
  46. trame_vtkjs/widgets/vtk_dependencies.py +137 -0
  47. trame_vtkjs/widgets/vtkjs_base.py +263 -0
  48. trame_vtkjs/widgets/vtkjs_shared_view.py +11 -0
  49. trame_vtkjs/widgets/vtkjs_view.py +41 -0
  50. trame_vtkjs/wire.py +86 -0
  51. trame_vtkjs-0.1.0.dist-info/METADATA +76 -0
  52. trame_vtkjs-0.1.0.dist-info/RECORD +54 -0
  53. trame_vtkjs-0.1.0.dist-info/WHEEL +4 -0
  54. trame_vtkjs-0.1.0.dist-info/licenses/LICENSE +15 -0
trame/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __path__ = __import__("pkgutil").extend_path(__path__, __name__)
@@ -0,0 +1 @@
1
+ __path__ = __import__("pkgutil").extend_path(__path__, __name__)
trame/modules/vtkjs.py ADDED
@@ -0,0 +1 @@
1
+ from trame_vtkjs.module import * # noqa F403
@@ -0,0 +1 @@
1
+ __path__ = __import__("pkgutil").extend_path(__path__, __name__)
trame/widgets/vtkjs.py ADDED
@@ -0,0 +1,9 @@
1
+ from trame_vtkjs.widgets.vtkjs_view import * # noqa F403
2
+ from trame_vtkjs.widgets.vtkjs_shared_view import * # noqa F403
3
+ from trame_vtkjs import host_types as _host_types
4
+
5
+
6
+ def initialize(server: "_host_types.ModuleHostServer") -> None:
7
+ from trame_vtkjs import module
8
+
9
+ server.enable_module(module)
@@ -0,0 +1,39 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, Union
4
+
5
+ from trame_client.utils.version import get_version
6
+
7
+ from trame_vtkjs.view_types import Tiles3DQualityPolicy, Tiles3DTexturePolicy
8
+
9
+ if TYPE_CHECKING:
10
+ from trame_vtkjs.streamed_scene import (
11
+ PointCloudSource,
12
+ StreamedSceneActor,
13
+ Tiles3DSource,
14
+ )
15
+
16
+ __version__: str = get_version("trame-vtkjs")
17
+
18
+ __all__ = [
19
+ "PointCloudSource",
20
+ "StreamedSceneActor",
21
+ "Tiles3DSource",
22
+ "Tiles3DQualityPolicy",
23
+ "Tiles3DTexturePolicy",
24
+ "__version__",
25
+ ]
26
+
27
+
28
+ def __getattr__(
29
+ name: str,
30
+ ) -> type[Union[PointCloudSource, StreamedSceneActor, Tiles3DSource]]:
31
+ # Resolved lazily so trame_vtkjs.store and trame_vtkjs.wire import
32
+ # without VTK or a built web bundle.
33
+ if name in {"PointCloudSource", "StreamedSceneActor", "Tiles3DSource"}:
34
+ from trame_vtkjs import streamed_scene
35
+
36
+ public_type: type[Union[PointCloudSource, StreamedSceneActor, Tiles3DSource]]
37
+ public_type = getattr(streamed_scene, name)
38
+ return public_type
39
+ raise AttributeError(name)
@@ -0,0 +1,43 @@
1
+ """Structural types for the trame and wslink objects the package is handed.
2
+
3
+ trame and wslink ship no type information, so each Protocol names only the
4
+ members this package calls.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Callable
10
+ from types import ModuleType
11
+ from typing import TYPE_CHECKING, Protocol
12
+
13
+ if TYPE_CHECKING:
14
+ from trame_vtkjs.module.protocol import ObjectManagerAPI
15
+
16
+
17
+ class NamedServer(Protocol):
18
+ """A trame server as far as per-server module state needs it."""
19
+
20
+ @property
21
+ def name(self) -> str: ...
22
+
23
+
24
+ class LinkProtocolRoot(Protocol):
25
+ """The wslink server protocol handed to protocol configuration callbacks."""
26
+
27
+ def registerLinkProtocol(self, protocol: ObjectManagerAPI, /) -> object: ...
28
+
29
+
30
+ class ProtocolHostServer(NamedServer, Protocol):
31
+ """A trame server that registers wslink protocols once it starts."""
32
+
33
+ def add_protocol_to_configure(
34
+ self, configure_protocol_fn: Callable[[LinkProtocolRoot], None], /
35
+ ) -> object: ...
36
+
37
+
38
+ class ModuleHostServer(NamedServer, Protocol):
39
+ """A trame server that can enable a module definition."""
40
+
41
+ def enable_module(
42
+ self, module: ModuleType | dict[str, object], /, **kwargs: object
43
+ ) -> object: ...
@@ -0,0 +1,122 @@
1
+ """Pickable-mapper marking for the fork interaction seam.
2
+
3
+ Tagging a server-side glyph mapper as pickable makes the translator emit a
4
+ ``pickable`` block on its serialized node. The block is opaque to the fork: the
5
+ app puts in whatever ``tags``/``ids`` it needs and the client round-trips them
6
+ verbatim through ``pickAt``. The fork never interprets tag semantics — it only
7
+ answers "what rendered glyph point is under (x, y)".
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import math
13
+ from collections.abc import Iterable, Mapping
14
+ from typing import TYPE_CHECKING, Literal, SupportsFloat, SupportsInt, TypedDict, cast
15
+
16
+ from trame_vtkjs.module.feature_blocks import get_block, set_block
17
+ from trame_vtkjs.module.validation import positive_finite
18
+
19
+ __all__ = [
20
+ "PickPreview",
21
+ "PickPlane",
22
+ "PickableConfig",
23
+ "make_pickable",
24
+ "clear_pickable",
25
+ "pickable_config",
26
+ ]
27
+
28
+ if TYPE_CHECKING:
29
+ from vtkmodules.vtkCommonCore import vtkObjectBase
30
+ from vtkmodules.vtkRenderingCore import vtkMapper
31
+
32
+ PICKABLE_STATE_KEY = "pickable"
33
+
34
+ PickPreview = Literal["screen", "plane", "cloud"]
35
+
36
+
37
+ class PickPlane(TypedDict):
38
+ origin: list[float]
39
+ normal: list[float]
40
+
41
+
42
+ class _PickableFields(TypedDict):
43
+ tags: dict[str, object]
44
+ ids: list[object] | None
45
+ grabPx: float
46
+ priority: int
47
+ preview: PickPreview | None
48
+
49
+
50
+ class PickableConfig(_PickableFields, total=False):
51
+ """The ``pickable`` block; ``plane`` is present only when one was given."""
52
+
53
+ plane: PickPlane
54
+ previewGroup: str
55
+
56
+
57
+ def make_pickable(
58
+ mapper: vtkMapper,
59
+ tags: Mapping[str, object] | None = None,
60
+ ids: Iterable[object] | None = None,
61
+ *,
62
+ grab_px: SupportsFloat,
63
+ priority: SupportsInt = 0,
64
+ preview: PickPreview | None = None,
65
+ preview_group: str | None = None,
66
+ plane: Mapping[str, Iterable[SupportsFloat]] | None = None,
67
+ ) -> PickableConfig:
68
+ """Mark ``mapper`` pickable and stamp its opaque hit-test metadata.
69
+
70
+ ``tags`` (dict) and ``ids`` (list, one entry per glyph point) are opaque to
71
+ the fork and round-tripped verbatim. ``grab_px`` is the CSS-pixel grab
72
+ radius; ``priority`` breaks ties between overlapping pickables (higher
73
+ wins). Re-calling with a changed config replaces it and bumps the mapper's
74
+ MTime so the next push re-serializes it (reaching the client as a patch
75
+ op); an unchanged config is a no-op, so callers can re-tag on every update
76
+ without forcing spurious re-serialization. ``preview_group`` explicitly
77
+ groups render buckets sharing one coordinate system and stable point ids.
78
+ A point id must be unique across all buckets within that group.
79
+ """
80
+ grab = positive_finite(grab_px, "grab_px must be a positive number")
81
+ if preview not in (None, "screen", "plane", "cloud"):
82
+ raise ValueError("preview must be None, 'screen', 'plane', or 'cloud'")
83
+ normalized_plane: PickPlane | None = None
84
+ if plane is not None:
85
+ if not isinstance(plane, Mapping):
86
+ raise ValueError("plane must contain origin and normal vectors")
87
+ origin = [float(value) for value in plane.get("origin", ())]
88
+ normal = [float(value) for value in plane.get("normal", ())]
89
+ if (
90
+ len(origin) != 3
91
+ or len(normal) != 3
92
+ or not all(math.isfinite(value) for value in (*origin, *normal))
93
+ or sum(value * value for value in normal) == 0
94
+ ):
95
+ raise ValueError("plane must contain finite 3D origin and normal vectors")
96
+ normalized_plane = {"origin": origin, "normal": normal}
97
+ if preview == "plane" and normalized_plane is None:
98
+ raise ValueError("preview='plane' requires a plane")
99
+
100
+ config: PickableConfig = {
101
+ "tags": dict(tags) if tags else {},
102
+ "ids": list(ids) if ids is not None else None,
103
+ "grabPx": grab,
104
+ "priority": int(priority),
105
+ "preview": preview,
106
+ }
107
+ if preview_group is not None:
108
+ if not isinstance(preview_group, str) or not preview_group or ids is None:
109
+ raise ValueError("preview_group requires a nonempty string and point ids")
110
+ config["previewGroup"] = preview_group
111
+ if normalized_plane is not None:
112
+ config["plane"] = normalized_plane
113
+ set_block(mapper, PICKABLE_STATE_KEY, config)
114
+ return config
115
+
116
+
117
+ def clear_pickable(mapper: vtkMapper) -> None:
118
+ set_block(mapper, PICKABLE_STATE_KEY, None)
119
+
120
+
121
+ def pickable_config(mapper: vtkObjectBase | None) -> PickableConfig | None:
122
+ return cast("PickableConfig | None", get_block(mapper, PICKABLE_STATE_KEY))
@@ -0,0 +1,47 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+ from typing import TYPE_CHECKING
5
+
6
+ from trame_vtkjs.module.protocol import ObjectManagerHelper
7
+
8
+ if TYPE_CHECKING:
9
+ from trame_vtkjs.host_types import NamedServer, ProtocolHostServer
10
+
11
+ # trame's enable_module() reads serve/scripts/vue_use/setup off this module by
12
+ # name, so every one of them is load-bearing despite having no in-tree caller.
13
+ __all__ = [
14
+ "serve",
15
+ "scripts",
16
+ "vue_use",
17
+ "setup",
18
+ "get_helper",
19
+ ]
20
+
21
+ serve_root = Path(__file__).with_name("serve").resolve()
22
+ serve_path = str(serve_root)
23
+
24
+
25
+ def _versioned_asset(asset_name: str) -> str:
26
+ asset_path = serve_root / "js" / asset_name
27
+ version = int(asset_path.stat().st_mtime)
28
+ return f"__trame_vtkjs/js/{asset_name}?v={version}"
29
+
30
+
31
+ serve = {"__trame_vtkjs": serve_path}
32
+ scripts = [_versioned_asset("trame_vtkjs.umd.js")]
33
+ vue_use = ["trame_vtkjs"]
34
+
35
+ # -----------------------------------------------------------------------------
36
+ # Module advanced initialization
37
+ # -----------------------------------------------------------------------------
38
+
39
+ HELPERS_PER_SERVER: dict[str, ObjectManagerHelper] = {}
40
+
41
+
42
+ def get_helper(server: NamedServer) -> ObjectManagerHelper | None:
43
+ return HELPERS_PER_SERVER.get(server.name)
44
+
45
+
46
+ def setup(trame_server: ProtocolHostServer, **kwargs: object) -> None:
47
+ HELPERS_PER_SERVER[trame_server.name] = ObjectManagerHelper(trame_server)
@@ -0,0 +1,98 @@
1
+ """VTK array scalar type -> JS typed-array constructor.
2
+
3
+ The one place that decides how a dataset array's bytes are reinterpreted
4
+ on the client; a wrong answer here silently corrupts every value in the
5
+ array rather than failing.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from vtkmodules.util import vtkConstants
11
+
12
+ # JS typed-array constructor per VTK scalar type, keyed by the type *constant
13
+ # name*; the numeric GetDataType() ids are resolved from vtkConstants below,
14
+ # never hand-written (VTK 9.x transposes them — UNSIGNED_CHAR=3, SHORT=4,
15
+ # UNSIGNED_SHORT=5, SIGNED_CHAR=15).
16
+ VTK_DATATYPE_JS_BY_NAME: dict[str, str] = {
17
+ "VTK_BIT": "Uint8Array", # packed bits; unsigned storage on the client
18
+ "VTK_CHAR": "Int8Array",
19
+ "VTK_SIGNED_CHAR": "Int8Array",
20
+ "VTK_UNSIGNED_CHAR": "Uint8Array",
21
+ "VTK_SHORT": "Int16Array",
22
+ "VTK_UNSIGNED_SHORT": "Uint16Array",
23
+ "VTK_INT": "Int32Array",
24
+ "VTK_UNSIGNED_INT": "Uint32Array",
25
+ "VTK_LONG": "BigInt64Array",
26
+ "VTK_UNSIGNED_LONG": "BigUint64Array",
27
+ "VTK_FLOAT": "Float32Array",
28
+ "VTK_DOUBLE": "Float64Array",
29
+ "VTK_ID_TYPE": "BigInt64Array",
30
+ "VTK_LONG_LONG": "BigInt64Array",
31
+ "VTK_UNSIGNED_LONG_LONG": "BigUint64Array",
32
+ }
33
+
34
+ VTK_DATATYPE_MAP: dict[int, str] = {
35
+ getattr(vtkConstants, name): js_type
36
+ for name, js_type in VTK_DATATYPE_JS_BY_NAME.items()
37
+ if hasattr(vtkConstants, name)
38
+ }
39
+
40
+ # Concrete VTK array class -> JS typed array; preferred over the numeric map
41
+ # (unambiguous, version-independent). numpy_to_vtk emits the fixed-width
42
+ # vtkType* classes (uint8 RGB -> vtkTypeUInt8Array), so keep them all present.
43
+ CLASS_TO_DATATYPE: dict[str, str] = {
44
+ "vtkFloatArray": "Float32Array",
45
+ "vtkDoubleArray": "Float64Array",
46
+ "vtkIntArray": "Int32Array",
47
+ "vtkUnsignedIntArray": "Uint32Array",
48
+ "vtkShortArray": "Int16Array",
49
+ "vtkUnsignedShortArray": "Uint16Array",
50
+ "vtkCharArray": "Int8Array",
51
+ "vtkSignedCharArray": "Int8Array",
52
+ "vtkUnsignedCharArray": "Uint8Array",
53
+ "vtkLongArray": "BigInt64Array",
54
+ "vtkUnsignedLongArray": "BigUint64Array",
55
+ "vtkLongLongArray": "BigInt64Array",
56
+ "vtkUnsignedLongLongArray": "BigUint64Array",
57
+ "vtkIdTypeArray": "BigInt64Array",
58
+ "vtkTypeInt8Array": "Int8Array",
59
+ "vtkTypeUInt8Array": "Uint8Array",
60
+ "vtkTypeInt16Array": "Int16Array",
61
+ "vtkTypeUInt16Array": "Uint16Array",
62
+ "vtkTypeInt32Array": "Int32Array",
63
+ "vtkTypeUInt32Array": "Uint32Array",
64
+ "vtkTypeInt64Array": "BigInt64Array",
65
+ "vtkTypeUInt64Array": "BigUint64Array",
66
+ "vtkTypeFloat32Array": "Float32Array",
67
+ "vtkTypeFloat64Array": "Float64Array",
68
+ }
69
+
70
+
71
+ def js_datatype(
72
+ class_name: str, data_type: int | None, *, missing_default: str | None = None
73
+ ) -> str:
74
+ """JS typed-array constructor for a VTK array.
75
+
76
+ A concrete VTK class wins over its numeric id. Unknown numeric ids must
77
+ not silently reinterpret their payload as Float32. Callers handling
78
+ genuinely absent serializer metadata can deliberately provide a default.
79
+ """
80
+ class_type = CLASS_TO_DATATYPE.get(class_name)
81
+ if class_type is not None:
82
+ return class_type
83
+
84
+ numeric_type = None if data_type is None else VTK_DATATYPE_MAP.get(data_type)
85
+ if numeric_type is not None:
86
+ return numeric_type
87
+
88
+ if data_type is None and missing_default is not None:
89
+ return missing_default
90
+
91
+ if data_type is None:
92
+ raise ValueError(
93
+ "VTK array datatype metadata is missing "
94
+ f"for class {class_name!r}; no client typed-array contract is available"
95
+ )
96
+ raise ValueError(
97
+ f"unsupported VTK numeric array datatype {data_type!r} for class {class_name!r}"
98
+ )
@@ -0,0 +1,40 @@
1
+ """Translate mapper-relative offsets; adapt VTK's mutable output parameters."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Callable, SupportsFloat, cast
6
+ from vtkmodules.vtkCommonCore import reference
7
+ from vtkmodules.vtkRenderingCore import vtkMapper
8
+
9
+ # VTK 9.6 stubs describe these mutable output references as input floats.
10
+ # The runtime fills reference objects and they implement the numeric protocol.
11
+ OffsetGetter = Callable[[reference, reference], None]
12
+
13
+
14
+ def coincident_topology_block(mapper: vtkMapper) -> dict[str, object] | None:
15
+ if mapper.GetResolveCoincidentTopology() != 1:
16
+ return None
17
+
18
+ line_factor, line_units = reference(0.0), reference(0.0)
19
+ polygon_factor, polygon_units = reference(0.0), reference(0.0)
20
+ cast(OffsetGetter, mapper.GetRelativeCoincidentTopologyLineOffsetParameters)(
21
+ line_factor, line_units
22
+ )
23
+ cast(OffsetGetter, mapper.GetRelativeCoincidentTopologyPolygonOffsetParameters)(
24
+ polygon_factor, polygon_units
25
+ )
26
+ if not any(
27
+ float(cast(SupportsFloat, value))
28
+ for value in (line_factor, line_units, polygon_factor, polygon_units)
29
+ ):
30
+ return None
31
+ return {
32
+ "line": {
33
+ "factor": float(cast(SupportsFloat, line_factor)),
34
+ "offset": float(cast(SupportsFloat, line_units)),
35
+ },
36
+ "polygon": {
37
+ "factor": float(cast(SupportsFloat, polygon_factor)),
38
+ "offset": float(cast(SupportsFloat, polygon_units)),
39
+ },
40
+ }
@@ -0,0 +1,89 @@
1
+ """Feature blocks stored on the VTK object they describe.
2
+
3
+ Every block on an object lives in one JSON object, keyed by block name, under a
4
+ string key in the object's own ``vtkInformation``: ``GetInformation()`` for an
5
+ algorithm (every mapper), and ``GetPropertyKeys()`` for a prop. The blocks live
6
+ and die with the C++ object, so they survive Python wrapper churn without a
7
+ registry, and the translator reads them back into ``node["blocks"][name]``.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ from collections.abc import Mapping
14
+ from typing import TYPE_CHECKING
15
+
16
+ from vtkmodules.vtkCommonCore import vtkInformation, vtkInformationStringKey
17
+ from vtkmodules.vtkCommonDataModel import vtkCompositeDataSet
18
+ from vtkmodules.vtkCommonExecutionModel import vtkAlgorithm
19
+ from vtkmodules.vtkRenderingCore import vtkProp
20
+
21
+ if TYPE_CHECKING:
22
+ from vtkmodules.vtkCommonCore import vtkObject, vtkObjectBase
23
+
24
+ # A key created from Python (vtkInformationStringKey.MakeKey) crashes VTK's
25
+ # static key manager when the process exits, so the blocks ride a key VTK
26
+ # defines. Nothing in VTK reads NAME from an algorithm's
27
+ # information or a prop's keys.
28
+ _BLOCKS_KEY: vtkInformationStringKey = vtkCompositeDataSet.NAME()
29
+
30
+
31
+ def _information(vtk_object: vtkObjectBase, create: bool) -> vtkInformation | None:
32
+ if isinstance(vtk_object, vtkAlgorithm):
33
+ algorithm_information: vtkInformation = vtk_object.GetInformation()
34
+ return algorithm_information
35
+ if isinstance(vtk_object, vtkProp):
36
+ information: vtkInformation | None = vtk_object.GetPropertyKeys()
37
+ if information is None and create:
38
+ information = vtkInformation()
39
+ vtk_object.SetPropertyKeys(information)
40
+ return information
41
+ raise TypeError(f"{vtk_object.GetClassName()} cannot carry a feature block")
42
+
43
+
44
+ def _blocks(information: vtkInformation | None) -> dict[str, dict[str, object]]:
45
+ if information is None or not information.Has(_BLOCKS_KEY):
46
+ return {}
47
+ blocks: object = json.loads(_BLOCKS_KEY.Get(information))
48
+ if not isinstance(blocks, dict) or not all(
49
+ isinstance(block, dict) for block in blocks.values()
50
+ ):
51
+ raise RuntimeError("feature blocks are not a JSON object of objects")
52
+ return blocks
53
+
54
+
55
+ def get_block(vtk_object: vtkObjectBase | None, name: str) -> dict[str, object] | None:
56
+ """The named block on ``vtk_object``, or None when it carries none."""
57
+ if vtk_object is None:
58
+ return None
59
+ return _blocks(_information(vtk_object, create=False)).get(name)
60
+
61
+
62
+ def set_block(
63
+ vtk_object: vtkObject, name: str, block: Mapping[str, object] | None
64
+ ) -> bool:
65
+ """Store (or, with None, remove) one block; True when it changed.
66
+
67
+ Only a change bumps the object's MTime, so callers may re-apply the same
68
+ block on every update without forcing a re-serialization.
69
+ """
70
+ information = _information(vtk_object, create=block is not None)
71
+ if information is None:
72
+ return False
73
+ blocks = _blocks(information)
74
+ if block is None:
75
+ if blocks.pop(name, None) is None:
76
+ return False
77
+ else:
78
+ # Compared encoded, so a block equal to the stored one after the JSON
79
+ # round trip (tuples read back as lists) is not a change.
80
+ encoded = json.dumps(block, sort_keys=True)
81
+ if name in blocks and json.dumps(blocks[name], sort_keys=True) == encoded:
82
+ return False
83
+ blocks[name] = json.loads(encoded)
84
+ if blocks:
85
+ _BLOCKS_KEY.Set(information, json.dumps(blocks, sort_keys=True))
86
+ else:
87
+ information.Remove(_BLOCKS_KEY)
88
+ vtk_object.Modified()
89
+ return True