ocp-viewer-cadinterface 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.
- ocp_viewer_cadinterface/__init__.py +10 -0
- ocp_viewer_cadinterface/_read.py +166 -0
- ocp_viewer_cadinterface/_version.py +24 -0
- ocp_viewer_cadinterface/show.py +247 -0
- ocp_viewer_cadinterface-0.1.0.dist-info/METADATA +115 -0
- ocp_viewer_cadinterface-0.1.0.dist-info/RECORD +9 -0
- ocp_viewer_cadinterface-0.1.0.dist-info/WHEEL +4 -0
- ocp_viewer_cadinterface-0.1.0.dist-info/entry_points.txt +2 -0
- ocp_viewer_cadinterface-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""Show any object that implements ``__cad_interface__`` in the OCP viewers.
|
|
2
|
+
|
|
3
|
+
Installing the package is all it takes: the viewers import
|
|
4
|
+
``ocp_viewer_cadinterface.show`` through its entry point. This module imports
|
|
5
|
+
nothing, so that importing the package registers nothing.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from ._version import __version__
|
|
9
|
+
|
|
10
|
+
__all__ = ["__version__"]
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""The shapes of a ``__cad_interface__`` result as OCCT shapes, and what the viewer
|
|
2
|
+
draws them as.
|
|
3
|
+
|
|
4
|
+
Everything here is OCCT's: once a result is read, the shapes take the viewer's OCCT
|
|
5
|
+
path, which tessellates and measures them.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import io
|
|
12
|
+
import os
|
|
13
|
+
import tempfile
|
|
14
|
+
from collections import OrderedDict
|
|
15
|
+
from collections.abc import Mapping
|
|
16
|
+
from types import ModuleType
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from ocp_tessellate._kernel import binding_of, kernel
|
|
20
|
+
from ocp_tessellate.convert import get_kind, get_type
|
|
21
|
+
from ocp_tessellate.ocp_utils.predicates import is_topods_compound
|
|
22
|
+
from ocp_tessellate.ocp_utils.topology import downcast, get_compound_type, get_edges, get_vertices
|
|
23
|
+
|
|
24
|
+
__all__ = ["ACCEPT", "classify", "read_shape"]
|
|
25
|
+
|
|
26
|
+
# most preferred first: "ocp" shares the producer's shape, the binary BREP is the
|
|
27
|
+
# fastest to read, STEP the slowest
|
|
28
|
+
ACCEPT = ["ocp", "brep_binary", "brep_text", "step"]
|
|
29
|
+
|
|
30
|
+
# what was read, by format and a digest of the bytes: each show asks the producer
|
|
31
|
+
# again, and a STEP file is only parsed once. Returning the same shape again also
|
|
32
|
+
# lets ocp-tessellate reuse its mesh.
|
|
33
|
+
_CACHE_SIZE = 128
|
|
34
|
+
_cache: OrderedDict[tuple[str, bytes], Any] = OrderedDict()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def read_shape(entry: Mapping[str, Any]) -> Any:
|
|
38
|
+
"""The ``TopoDS_Shape`` of a ShapeDict, downcast to its type."""
|
|
39
|
+
fmt = entry.get("format")
|
|
40
|
+
data = entry.get("data")
|
|
41
|
+
if fmt == "ocp":
|
|
42
|
+
binding = binding_of(data)
|
|
43
|
+
if binding is None or binding.__name__ != "OCP":
|
|
44
|
+
raise TypeError(f'__cad_interface__ format "ocp" needs an OCP TopoDS_Shape, not {type(data).__name__}')
|
|
45
|
+
return downcast(data)
|
|
46
|
+
if fmt not in _READERS:
|
|
47
|
+
raise ValueError(f"__cad_interface__ returned format {fmt!r}, which was not asked for (accept={ACCEPT})")
|
|
48
|
+
if not isinstance(data, (bytes, bytearray, memoryview)):
|
|
49
|
+
raise TypeError(f"__cad_interface__ format {fmt!r} needs bytes, not {type(data).__name__}")
|
|
50
|
+
data = bytes(data)
|
|
51
|
+
key = (fmt, hashlib.blake2b(_content(fmt, data), digest_size=16).digest())
|
|
52
|
+
shape = _cache.get(key)
|
|
53
|
+
if shape is None:
|
|
54
|
+
shape = downcast(_READERS[fmt](kernel(), data))
|
|
55
|
+
_cache[key] = shape
|
|
56
|
+
if len(_cache) > _CACHE_SIZE:
|
|
57
|
+
_cache.popitem(last=False)
|
|
58
|
+
else:
|
|
59
|
+
_cache.move_to_end(key)
|
|
60
|
+
return shape
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _content(fmt: str, data: bytes) -> bytes:
|
|
64
|
+
"""What decides the shape: a STEP file's header holds a time stamp, which differs
|
|
65
|
+
each time a producer writes the same shape."""
|
|
66
|
+
if fmt == "step":
|
|
67
|
+
start = data.find(b"\nDATA;")
|
|
68
|
+
if start >= 0:
|
|
69
|
+
return data[start:]
|
|
70
|
+
return data
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _read_brep_text(k: ModuleType, data: bytes) -> Any:
|
|
74
|
+
shape = k.TopoDS.TopoDS_Shape()
|
|
75
|
+
builder = k.BRep.BRep_Builder()
|
|
76
|
+
# OCP takes a bytes stream, nanocct a text stream
|
|
77
|
+
stream = io.BytesIO(data) if k.__name__ == "OCP" else io.StringIO(data.decode("latin-1"))
|
|
78
|
+
try:
|
|
79
|
+
k.BRepTools.BRepTools.Read_s(shape, stream, builder)
|
|
80
|
+
except Exception: # noqa: BLE001 # a binding without stream support reads a file
|
|
81
|
+
with _temp_file(data, ".brep") as path:
|
|
82
|
+
k.BRepTools.BRepTools.Read_s(shape, path, builder)
|
|
83
|
+
return _checked(shape, "brep_text")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _read_brep_binary(k: ModuleType, data: bytes) -> Any:
|
|
87
|
+
shape = k.TopoDS.TopoDS_Shape()
|
|
88
|
+
try:
|
|
89
|
+
k.BinTools.BinTools.Read_s(shape, io.BytesIO(data))
|
|
90
|
+
except Exception: # noqa: BLE001
|
|
91
|
+
with _temp_file(data, ".bin.brep") as path:
|
|
92
|
+
k.BinTools.BinTools.Read_s(shape, path)
|
|
93
|
+
return _checked(shape, "brep_binary")
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _read_step(k: ModuleType, data: bytes) -> Any:
|
|
97
|
+
reader = k.STEPControl.STEPControl_Reader()
|
|
98
|
+
with _temp_file(data, ".step") as path:
|
|
99
|
+
status = reader.ReadFile(path)
|
|
100
|
+
if status != k.IFSelect.IFSelect_RetDone:
|
|
101
|
+
raise ValueError(f"__cad_interface__ returned STEP data that OCCT cannot read ({status})")
|
|
102
|
+
reader.TransferRoots()
|
|
103
|
+
return _checked(reader.OneShape(), "step")
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _checked(shape: Any, fmt: str) -> Any:
|
|
107
|
+
if shape.IsNull():
|
|
108
|
+
raise ValueError(f"__cad_interface__ returned {fmt!r} data without a shape")
|
|
109
|
+
return shape
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class _temp_file: # a context manager, used like a function
|
|
113
|
+
"""A temporary file holding `data`, removed afterwards."""
|
|
114
|
+
|
|
115
|
+
def __init__(self, data: bytes, suffix: str):
|
|
116
|
+
self.data, self.suffix = data, suffix
|
|
117
|
+
|
|
118
|
+
def __enter__(self) -> str:
|
|
119
|
+
fd, self.path = tempfile.mkstemp(suffix=self.suffix, prefix="cadinterface-")
|
|
120
|
+
with os.fdopen(fd, "wb") as f:
|
|
121
|
+
f.write(self.data)
|
|
122
|
+
return self.path
|
|
123
|
+
|
|
124
|
+
def __exit__(self, *exc: object) -> None:
|
|
125
|
+
os.unlink(self.path)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
_READERS = {"brep_binary": _read_brep_binary, "brep_text": _read_brep_text, "step": _read_step}
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def classify(shape: Any) -> tuple[str, str, Any]:
|
|
132
|
+
"""What the viewer draws `shape` as, as OCCT's own path does for a raw shape:
|
|
133
|
+
``(kind, type name, payload)``.
|
|
134
|
+
|
|
135
|
+
- kind ``"solid"`` or ``"face"`` (faces and shells): the payload is the shape
|
|
136
|
+
- kind ``"edge"`` (edges and wires) or ``"vertex"``: the payload is a list of them
|
|
137
|
+
- kind ``"mixed"``: a compound of shapes of several kinds, the payload is the list
|
|
138
|
+
of its direct children, each to be classified on its own
|
|
139
|
+
- kind ``"empty"``: a compound without shapes, the payload is None
|
|
140
|
+
"""
|
|
141
|
+
shape = downcast(shape)
|
|
142
|
+
if is_topods_compound(shape):
|
|
143
|
+
typ = get_compound_type(shape)
|
|
144
|
+
if typ is None:
|
|
145
|
+
return "empty", "Compound", None
|
|
146
|
+
if typ == "mixed":
|
|
147
|
+
return "mixed", "Compound", _children(shape)
|
|
148
|
+
else:
|
|
149
|
+
typ = get_type(shape)
|
|
150
|
+
kind = get_kind(typ)
|
|
151
|
+
if kind == "edge":
|
|
152
|
+
return kind, typ, list(get_edges(shape))
|
|
153
|
+
if kind == "vertex":
|
|
154
|
+
return kind, typ, list(get_vertices(shape))
|
|
155
|
+
return kind, typ, shape
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _children(compound: Any) -> list[Any]:
|
|
159
|
+
k = binding_of(compound)
|
|
160
|
+
assert k is not None, "an OCCT compound"
|
|
161
|
+
result = []
|
|
162
|
+
iterator = k.TopoDS.TopoDS_Iterator(compound)
|
|
163
|
+
while iterator.More():
|
|
164
|
+
result.append(downcast(iterator.Value()))
|
|
165
|
+
iterator.Next()
|
|
166
|
+
return result
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# file generated by vcs-versioning
|
|
2
|
+
# don't change, don't track in version control
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"__version__",
|
|
7
|
+
"__version_tuple__",
|
|
8
|
+
"version",
|
|
9
|
+
"version_tuple",
|
|
10
|
+
"__commit_id__",
|
|
11
|
+
"commit_id",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
version: str
|
|
15
|
+
__version__: str
|
|
16
|
+
__version_tuple__: tuple[int | str, ...]
|
|
17
|
+
version_tuple: tuple[int | str, ...]
|
|
18
|
+
commit_id: str | None
|
|
19
|
+
__commit_id__: str | None
|
|
20
|
+
|
|
21
|
+
__version__ = version = '0.1.0'
|
|
22
|
+
__version_tuple__ = version_tuple = (0, 1, 0)
|
|
23
|
+
|
|
24
|
+
__commit_id__ = commit_id = None
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"""What makes the viewers' ``show`` and ``show_all`` take any object that implements
|
|
2
|
+
``__cad_interface__``. Importing this module registers it, which the entry point of
|
|
3
|
+
the group ``ocp_viewer.kernels.show`` does in the user's process.
|
|
4
|
+
|
|
5
|
+
Every result becomes OCCT shapes, which take the viewer's OCCT path: OCCT tessellates
|
|
6
|
+
them, and the measurement backend measures them as OCCT shapes. So the plugin has no
|
|
7
|
+
tessellation and no backend of its own: ``ocp_tessellate`` hands an OCCT shape to OCCT,
|
|
8
|
+
whichever plugin made it.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from collections.abc import Mapping, Sequence
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
import numpy as np
|
|
17
|
+
from ocp_tessellate.ocp_utils.bbox import BoundingBox, bounding_box
|
|
18
|
+
from ocp_tessellate.plugin import OcpObject, Placement, ShowProtocol, TessellationProtocol, register_show
|
|
19
|
+
from ocp_tessellate.utils import Color
|
|
20
|
+
|
|
21
|
+
from ._read import ACCEPT, classify, read_shape
|
|
22
|
+
|
|
23
|
+
__all__ = ["KERNEL", "CadInterfaceShow"]
|
|
24
|
+
|
|
25
|
+
KERNEL = "cadinterface"
|
|
26
|
+
|
|
27
|
+
# Libraries that ocp-tessellate draws itself. Their objects keep that richer path
|
|
28
|
+
# (joints, parents, their own colours) also once they implement the protocol, since
|
|
29
|
+
# the viewer asks plugins before its own dispatch.
|
|
30
|
+
NATIVE = frozenset({"build123d", "cadquery"})
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class _Item:
|
|
34
|
+
"""A node of a converted result: an optional OCCT shape and children, with the
|
|
35
|
+
node's own placement and its effective colour. Plugin-owned, so that `convert` is
|
|
36
|
+
called for it and can give it its colour: the pipeline gives the children of a
|
|
37
|
+
container only the container's colour."""
|
|
38
|
+
|
|
39
|
+
__slots__ = ("_name", "children", "color", "placement", "shape")
|
|
40
|
+
|
|
41
|
+
def __init__(
|
|
42
|
+
self,
|
|
43
|
+
name: str | None,
|
|
44
|
+
shape: Any = None,
|
|
45
|
+
color: tuple[float, float, float, float] | None = None,
|
|
46
|
+
placement: Placement | None = None,
|
|
47
|
+
children: Sequence[_Item] = (),
|
|
48
|
+
):
|
|
49
|
+
self._name = name
|
|
50
|
+
self.shape = shape
|
|
51
|
+
self.color = color
|
|
52
|
+
self.placement = placement
|
|
53
|
+
self.children = list(children)
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def name(self) -> str:
|
|
57
|
+
"""The name the viewer gives the node when `show` gives it none: its own, else
|
|
58
|
+
the type of its shape, as for an OCCT shape, else that of a group."""
|
|
59
|
+
if self._name is not None:
|
|
60
|
+
return self._name
|
|
61
|
+
if self.shape is not None and not self.children:
|
|
62
|
+
return classify(self.shape)[1]
|
|
63
|
+
return "Group"
|
|
64
|
+
|
|
65
|
+
def __repr__(self) -> str:
|
|
66
|
+
return f"_Item(name={self._name!r}, shape={type(self.shape).__name__}, children={len(self.children)})"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def is_producer(obj: object) -> bool:
|
|
70
|
+
"""Whether `obj` implements ``__cad_interface__`` and is not an object that
|
|
71
|
+
ocp-tessellate draws itself, also through a subclass defined elsewhere."""
|
|
72
|
+
cls = type(obj)
|
|
73
|
+
return callable(getattr(cls, "__cad_interface__", None)) and not any(
|
|
74
|
+
base.__module__.partition(".")[0] in NATIVE for base in cls.__mro__
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _call(obj: object) -> Any:
|
|
79
|
+
return obj.__cad_interface__(accept=list(ACCEPT)) # type: ignore[attr-defined]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _checked(obj: object, result: Any, expected: str | None = None) -> Mapping[str, Any]:
|
|
83
|
+
"""A ShapeDict or AssemblyDict of version 1, or with `expected` one of that type: the
|
|
84
|
+
top-level result and every entry of an assembly's ``shapes``."""
|
|
85
|
+
what = f"{type(obj).__name__}.__cad_interface__ returned"
|
|
86
|
+
if expected is not None:
|
|
87
|
+
what += " an assembly with"
|
|
88
|
+
if not isinstance(result, Mapping):
|
|
89
|
+
raise TypeError(f"{what} a {type(result).__name__}, not a dict")
|
|
90
|
+
if result.get("version") != 1:
|
|
91
|
+
raise ValueError(f"{what} version {result.get('version')!r}; ocp-viewer-cadinterface reads version 1")
|
|
92
|
+
if expected is not None and result.get("type") != expected:
|
|
93
|
+
raise ValueError(f"{what} a {result.get('type')!r} among its shapes")
|
|
94
|
+
return result
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _color(value: Any) -> tuple[float, float, float, float] | None:
|
|
98
|
+
if value is None:
|
|
99
|
+
return None
|
|
100
|
+
rgba = tuple(float(c) for c in value)
|
|
101
|
+
if len(rgba) != 4 or not all(0.0 <= c <= 1.0 for c in rgba):
|
|
102
|
+
raise ValueError(f"__cad_interface__ colour must be sRGBA in [0, 1], not {value!r}")
|
|
103
|
+
return rgba # type: ignore[return-value]
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _placement(matrix: Any) -> Placement:
|
|
107
|
+
m = np.asarray(matrix, dtype=np.float64)
|
|
108
|
+
if m.shape != (4, 4):
|
|
109
|
+
raise ValueError(f"__cad_interface__ location must be a 4x4 matrix, not of shape {m.shape}")
|
|
110
|
+
rotation = m[:3, :3]
|
|
111
|
+
if not (
|
|
112
|
+
np.allclose(m[3], (0, 0, 0, 1))
|
|
113
|
+
and np.allclose(rotation.T @ rotation, np.eye(3), atol=1e-9)
|
|
114
|
+
and np.linalg.det(rotation) > 0
|
|
115
|
+
):
|
|
116
|
+
raise ValueError(f"__cad_interface__ location must be a rigid transform, not {m.tolist()}")
|
|
117
|
+
return Placement.from_axes(tuple(m[:3, 3]), tuple(m[:3, 0]), tuple(m[:3, 2]))
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def to_item(obj: object) -> _Item:
|
|
121
|
+
"""The result of ``obj.__cad_interface__`` as a tree of OCCT shapes.
|
|
122
|
+
|
|
123
|
+
A shape is a node of its own; so is an assembly whose root has no name, the root
|
|
124
|
+
with its placement. An assembly whose root has a name holds the root as its one
|
|
125
|
+
child, so the name stays in the viewer's tree."""
|
|
126
|
+
result = _checked(obj, _call(obj))
|
|
127
|
+
kind = result.get("type")
|
|
128
|
+
if kind == "shape":
|
|
129
|
+
return _Item(None, read_shape(result))
|
|
130
|
+
if kind != "assembly":
|
|
131
|
+
raise ValueError(f"{type(obj).__name__}.__cad_interface__ returned unknown type {kind!r}")
|
|
132
|
+
|
|
133
|
+
# shared geometry is read once, and stays one shape: the viewer meshes it once
|
|
134
|
+
shapes = [read_shape(_checked(obj, entry, "shape")) for entry in result["shapes"]]
|
|
135
|
+
|
|
136
|
+
def node(n: Mapping[str, Any], inherited: tuple[float, float, float, float] | None) -> _Item:
|
|
137
|
+
color = _color(n.get("color")) or inherited # None inherits the parent's colour
|
|
138
|
+
index = n.get("shape")
|
|
139
|
+
return _Item(
|
|
140
|
+
n.get("name"),
|
|
141
|
+
None if index is None else shapes[index],
|
|
142
|
+
color,
|
|
143
|
+
_placement(n["location"]),
|
|
144
|
+
[node(child, color) for child in n.get("children", ())],
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
root = node(result["root"], None)
|
|
148
|
+
if root._name is None:
|
|
149
|
+
return root
|
|
150
|
+
return _Item(None, children=[root])
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _children_of(item: _Item) -> list[tuple[str | None, object, Placement | None]] | None:
|
|
154
|
+
"""The children of a node, None for one that is a single drawable shape."""
|
|
155
|
+
children: list[tuple[str | None, object, Placement | None]] = []
|
|
156
|
+
if item.shape is not None:
|
|
157
|
+
kind, typ, payload = classify(item.shape)
|
|
158
|
+
if kind == "mixed":
|
|
159
|
+
# a compound of several kinds: each part is drawn as what it is
|
|
160
|
+
children += [(None, _Item(None, part, item.color), None) for part in payload]
|
|
161
|
+
elif kind != "empty":
|
|
162
|
+
if not item.children:
|
|
163
|
+
return None
|
|
164
|
+
children.append((None, _Item(typ, item.shape, item.color), None))
|
|
165
|
+
children += [(None, child, None) for child in item.children]
|
|
166
|
+
return children
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
# The producer that `get_children` converted last, with the result. The pipeline asks
|
|
170
|
+
# `get_children` first about an object, then `convert` and `get_location` (or only
|
|
171
|
+
# `get_location`) about the same one; those reuse it, so a show calls the producer
|
|
172
|
+
# once. Each show starts with `get_children`, which always calls the producer, so a
|
|
173
|
+
# changed object is shown as it is now.
|
|
174
|
+
_last: tuple[object, _Item] | None = None
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _item_of(obj: object, *, fresh: bool = False) -> _Item:
|
|
178
|
+
global _last
|
|
179
|
+
if isinstance(obj, _Item):
|
|
180
|
+
return obj
|
|
181
|
+
if not fresh and _last is not None and _last[0] is obj:
|
|
182
|
+
return _last[1]
|
|
183
|
+
item = to_item(obj)
|
|
184
|
+
_last = (obj, item)
|
|
185
|
+
return item
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
class CadInterfaceShow(ShowProtocol):
|
|
189
|
+
def is_object(self, obj: object) -> bool:
|
|
190
|
+
"""An object that implements ``__cad_interface__``, unless build123d or CadQuery
|
|
191
|
+
draws it, or a node of one that was converted. Cheap: it does not call the
|
|
192
|
+
method."""
|
|
193
|
+
return isinstance(obj, _Item) or is_producer(obj)
|
|
194
|
+
|
|
195
|
+
def get_children(self, obj: object) -> list[tuple[str | None, object, Placement | None]] | None:
|
|
196
|
+
return _children_of(_item_of(obj, fresh=True))
|
|
197
|
+
|
|
198
|
+
def get_location(self, obj: object) -> Placement | None:
|
|
199
|
+
return _item_of(obj).placement
|
|
200
|
+
|
|
201
|
+
def convert(self, obj: object, name: str, color: Any, alpha: float | None, helper_scale: float) -> OcpObject:
|
|
202
|
+
"""A single shape as an OcpObject holding OCCT's shape. A colour passed to
|
|
203
|
+
``show`` wins over the producer's, and so does an alpha over its sRGBA alpha."""
|
|
204
|
+
item = _item_of(obj)
|
|
205
|
+
kind, _, payload = classify(item.shape)
|
|
206
|
+
assert kind not in ("mixed", "empty"), "get_children answers for those"
|
|
207
|
+
if color is not None:
|
|
208
|
+
rgba: Color | None = Color(color)
|
|
209
|
+
elif item.color is not None:
|
|
210
|
+
rgba = Color(item.color)
|
|
211
|
+
else:
|
|
212
|
+
rgba = None
|
|
213
|
+
if rgba is not None and alpha is not None:
|
|
214
|
+
rgba.a = alpha
|
|
215
|
+
return OcpObject(kind, payload, name=name, color=rgba)
|
|
216
|
+
|
|
217
|
+
def line(self, start: tuple[float, float, float], end: tuple[float, float, float]) -> Any:
|
|
218
|
+
raise NotImplementedError("ocp-viewer-cadinterface draws only OCCT shapes, which OCCT draws helpers for")
|
|
219
|
+
|
|
220
|
+
def serialize(self, shape: object) -> bytes:
|
|
221
|
+
raise NotImplementedError("ocp-viewer-cadinterface hands OCCT shapes to the backend, which OCCT serializes")
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
class _OcctTessellation(TessellationProtocol):
|
|
225
|
+
"""`convert` returns OCCT shapes, and ocp-tessellate tessellates those with OCCT, so
|
|
226
|
+
only `bounding_box` is called: for the extent of a scene, which sizes relative helpers,
|
|
227
|
+
ocp-tessellate asks about the plugin's objects before converting them."""
|
|
228
|
+
|
|
229
|
+
def tessellate(self, *args: Any, **kwargs: Any) -> Any:
|
|
230
|
+
raise NotImplementedError("OCCT tessellates the shapes of ocp-viewer-cadinterface")
|
|
231
|
+
|
|
232
|
+
def discretize_edges(self, *args: Any, **kwargs: Any) -> Any:
|
|
233
|
+
raise NotImplementedError("OCCT discretizes the edges of ocp-viewer-cadinterface")
|
|
234
|
+
|
|
235
|
+
def convert_vertices(self, *args: Any, **kwargs: Any) -> Any:
|
|
236
|
+
raise NotImplementedError("OCCT converts the vertices of ocp-viewer-cadinterface")
|
|
237
|
+
|
|
238
|
+
def bounding_box(self, shape: object) -> BoundingBox:
|
|
239
|
+
"""OCCT's box of the shape of a single drawable object, in its own frame: the
|
|
240
|
+
pipeline applies its placement."""
|
|
241
|
+
item = _item_of(shape)
|
|
242
|
+
if item.shape is None:
|
|
243
|
+
raise ValueError("a node without a shape has no bounding box of its own")
|
|
244
|
+
return bounding_box(item.shape)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
register_show(KERNEL, _OcctTessellation(), CadInterfaceShow(), api=1)
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: ocp-viewer-cadinterface
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Show any object that implements __cad_interface__ in the OCP viewers
|
|
5
|
+
Project-URL: Homepage, https://github.com/DavidMStraub/ocp-viewer-cadinterface
|
|
6
|
+
Project-URL: Protocol, https://github.com/DavidMStraub/cad-interface
|
|
7
|
+
Author: David Straub
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: build123d,cad,cad-interface,cadquery,occt,ocp,viewer
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Requires-Python: >=3.10
|
|
14
|
+
Requires-Dist: numpy
|
|
15
|
+
Requires-Dist: ocp-tessellate<3.8.0,>=3.7.0
|
|
16
|
+
Provides-Extra: test
|
|
17
|
+
Requires-Dist: build123d; extra == 'test'
|
|
18
|
+
Requires-Dist: ocp-viewer-core<1.3.0,>=1.2.0; extra == 'test'
|
|
19
|
+
Requires-Dist: ocp-vscode>=4.3; extra == 'test'
|
|
20
|
+
Requires-Dist: pytest; extra == 'test'
|
|
21
|
+
Requires-Dist: ruff; extra == 'test'
|
|
22
|
+
Requires-Dist: solidfunc>=0.1.0; extra == 'test'
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# ocp-viewer-cadinterface
|
|
26
|
+
|
|
27
|
+
A plugin for the OCP viewers ([OCP CAD Viewer for VS Code](https://github.com/bernhard-42/vscode-ocp-cad-viewer),
|
|
28
|
+
OCP Viewer, Jupyter CadQuery, build123d Studio). With it, `show` and `show_all` display any
|
|
29
|
+
object that implements the [`__cad_interface__`](https://github.com/DavidMStraub/cad-interface)
|
|
30
|
+
protocol, and the viewer's measurement tools work on it, including between it and build123d
|
|
31
|
+
or CadQuery objects in the same scene.
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
import build123d as bd
|
|
35
|
+
import solidfunc as sf # a CAD library on a non-OCCT kernel
|
|
36
|
+
from ocp_vscode import show
|
|
37
|
+
|
|
38
|
+
plate = sf.box(size_x=80, size_y=50, size_z=10) - sf.cylinder(diameter=20, height=10)
|
|
39
|
+
cube = bd.Pos(65, 0, 5) * bd.Box(10, 10, 10)
|
|
40
|
+
|
|
41
|
+
show(plate, cube, names=["plate", "cube"]) # measure the 20 mm between them in the viewer
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
[examples/demo.ipynb](examples/demo.ipynb) has the full example.
|
|
45
|
+
|
|
46
|
+
## Install
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
pip install ocp-viewer-cadinterface
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Install it in the environment your script runs in. Your script does not import it: the viewer
|
|
53
|
+
finds it through its entry point at the first `show`. A Jupyter kernel that has already shown
|
|
54
|
+
something needs a restart after the install.
|
|
55
|
+
|
|
56
|
+
The measurement backend's environment needs nothing extra, because the plugin hands only OCCT
|
|
57
|
+
shapes to the viewer (see below).
|
|
58
|
+
|
|
59
|
+
It needs ocp-tessellate 3.7 and, for the viewer, ocp-viewer-core 1.2 or later.
|
|
60
|
+
|
|
61
|
+
## What it shows
|
|
62
|
+
|
|
63
|
+
- A `ShapeDict` in any version 1 format: `"ocp"`, `"brep_binary"`, `"brep_text"`, `"step"`.
|
|
64
|
+
The plugin asks for them in that order. `"ocp"` shapes are used as they are, without a copy.
|
|
65
|
+
- An `AssemblyDict`: a tree of groups, with the nodes' names, locations and colours. A node
|
|
66
|
+
without a colour takes its parent's. Geometry used by several nodes is read and meshed once.
|
|
67
|
+
- Solids, shells, faces, wires, edges, vertices and compounds of them, including compounds that
|
|
68
|
+
mix several kinds.
|
|
69
|
+
|
|
70
|
+
Names, colours and alphas passed to `show` take precedence over the producer's, as the protocol
|
|
71
|
+
asks consumers to do. An unnamed shape is named by its type, as an OCCT shape is.
|
|
72
|
+
|
|
73
|
+
build123d and CadQuery objects, and objects of your own subclasses of their classes, are never
|
|
74
|
+
taken by this plugin, even once they implement the protocol. The viewer draws them itself, with more information (joints, parents, materials).
|
|
75
|
+
|
|
76
|
+
## How it works
|
|
77
|
+
|
|
78
|
+
Every result becomes OCCT shapes, read with the OCCT binding ocp-tessellate runs on. From there
|
|
79
|
+
the shapes take the viewer's OCCT path: OCCT tessellates them, and the measurement backend
|
|
80
|
+
measures them as OCCT shapes. So the plugin has only the drawing half of a
|
|
81
|
+
[kernel plugin](https://bernhard-42.github.io/ocp_viewer_docs/plugins/overview/), one module
|
|
82
|
+
registered through the entry point group `ocp_viewer.kernels.show`, and no tessellation and no
|
|
83
|
+
backend of its own.
|
|
84
|
+
|
|
85
|
+
Each `show` calls `__cad_interface__` once per object, so a changed object is shown as it is now. What
|
|
86
|
+
was read is cached by its content, so the same STEP data is parsed once (a STEP header's time
|
|
87
|
+
stamp is ignored), and OCCT reuses its mesh.
|
|
88
|
+
|
|
89
|
+
## Limits
|
|
90
|
+
|
|
91
|
+
- The viewer shows and measures OCCT's reading of the producer's data (for solidfunc, of its
|
|
92
|
+
STEP output), not the producer's kernel's own geometry. Showing a kernel's own geometry needs a
|
|
93
|
+
kernel plugin. The two complement each other: the protocol makes any library visible with one
|
|
94
|
+
method, and a kernel plugin makes one kernel first-class.
|
|
95
|
+
- Faces and edges can only be shown on their own if the producer implements the protocol on
|
|
96
|
+
them. A face picked in the viewer does not map back to the producer's face: names of
|
|
97
|
+
sub-shapes are not part of version 1 of the protocol.
|
|
98
|
+
- Kernel plugins are asked in no defined order. If a kernel with its own plugin also implemented
|
|
99
|
+
the protocol, both plugins would claim its objects.
|
|
100
|
+
|
|
101
|
+
## Development
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
python -m venv .venv && . .venv/bin/activate
|
|
105
|
+
pip install -e ".[test]"
|
|
106
|
+
pytest
|
|
107
|
+
ruff check . && ruff format --check .
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
The tests use producers written by hand with plain OCP, one per format, plus solidfunc and
|
|
111
|
+
build123d parts measured against each other through ocp-viewer-core's backend.
|
|
112
|
+
|
|
113
|
+
## Licence
|
|
114
|
+
|
|
115
|
+
MIT
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
ocp_viewer_cadinterface/__init__.py,sha256=E7vE0rg8spIa0RfRzWa0HKOZLnMS5_sEqhWManPqtw0,339
|
|
2
|
+
ocp_viewer_cadinterface/_read.py,sha256=fXPVKEcn6xRxd5LzqcQ0mHMaKrSBgeqolWvwe6-goxg,6135
|
|
3
|
+
ocp_viewer_cadinterface/_version.py,sha256=n_5vdJsPNu7wZ57LGuRL585uvll-hiuvZUBWzdG0RQU,520
|
|
4
|
+
ocp_viewer_cadinterface/show.py,sha256=IwDNivegI-Bddsu__WHHkDEHQB8xMGZAObpBxpGDAME,10592
|
|
5
|
+
ocp_viewer_cadinterface-0.1.0.dist-info/METADATA,sha256=Ojt1LPSfxeTk9X-kA8Aa4iEVDnaYLTMpl9Wby546450,5072
|
|
6
|
+
ocp_viewer_cadinterface-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
7
|
+
ocp_viewer_cadinterface-0.1.0.dist-info/entry_points.txt,sha256=hI2PHE5TVuvrWMxjRY3iJ3o0CfFCgL3tGMcxInnAhI4,70
|
|
8
|
+
ocp_viewer_cadinterface-0.1.0.dist-info/licenses/LICENSE,sha256=EeOmoLuI1JXZFv7pbM6W7jvlRBFw-H58Omi69v6gKso,1069
|
|
9
|
+
ocp_viewer_cadinterface-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 David Straub
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|