forked from tpaviot/pythonocc-core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDataExchange.py
More file actions
850 lines (705 loc) · 28.8 KB
/
DataExchange.py
File metadata and controls
850 lines (705 loc) · 28.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
##Copyright 2018-2024 Thomas Paviot (tpaviot@gmail.com)
##
##This file is part of pythonOCC.
##
##pythonOCC is free software: you can redistribute it and/or modify
##it under the terms of the GNU Lesser General Public License as published by
##the Free Software Foundation, either version 3 of the License, or
##(at your option) any later version.
##
##pythonOCC is distributed in the hope that it will be useful,
##but WITHOUT ANY WARRANTY; without even the implied warranty of
##MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
##GNU Lesser General Public License for more details.
##
##You should have received a copy of the GNU Lesser General Public License
##along with pythonOCC. If not, see <http://www.gnu.org/licenses/>.
import os
from typing import Union, List, Dict, Tuple, Any
from OCC.Core.TopoDS import TopoDS_Compound, TopoDS_Edge, TopoDS_Shape
from OCC.Core.BRepTools import breptools
from OCC.Core.BRepMesh import BRepMesh_IncrementalMesh
from OCC.Core.StlAPI import stlapi, StlAPI_Writer
from OCC.Core.BRep import BRep_Builder
from OCC.Core.gp import gp_Pnt, gp_Dir, gp_Pnt2d
from OCC.Core.Bnd import Bnd_Box2d
from OCC.Core.IGESControl import (
IGESControl_Controller,
IGESControl_Reader,
IGESControl_Writer,
)
from OCC.Core.STEPControl import (
STEPControl_Reader,
STEPControl_Writer,
STEPControl_AsIs,
)
from OCC.Core.Interface import Interface_Static
from OCC.Core.IFSelect import IFSelect_RetDone, IFSelect_ItemsByEntity
from OCC.Core.TDocStd import TDocStd_Document
from OCC.Core.XCAFDoc import (
XCAFDoc_DocumentTool,
XCAFDoc_ColorTool,
)
from OCC.Core.STEPCAFControl import STEPCAFControl_Reader
from OCC.Core.TDF import TDF_LabelSequence, TDF_Label
from OCC.Core.Quantity import Quantity_Color, Quantity_TOC_RGB
from OCC.Core.TopLoc import TopLoc_Location
from OCC.Core.BRepBuilderAPI import (
BRepBuilderAPI_Transform,
BRepBuilderAPI_Sewing,
BRepBuilderAPI_MakeSolid,
)
from OCC.Core.TColStd import TColStd_IndexedDataMapOfStringString
from OCC.Core.TCollection import TCollection_AsciiString
from OCC.Core.RWPly import RWPly_CafWriter
from OCC.Core.Message import Message_ProgressRange
from OCC.Core.RWGltf import RWGltf_CafReader, RWGltf_CafWriter
from OCC.Core.RWObj import RWObj_CafWriter
from OCC.Core.RWMesh import (
RWMesh_CoordinateSystem_posYfwd_posZup,
RWMesh_CoordinateSystem_negZfwd_posYup,
)
from OCC.Core.UnitsMethods import unitsmethods
from OCC.Extend.TopologyUtils import discretize_edge, get_sorted_hlr_edges
try:
import svgwrite
HAVE_SVGWRITE = True
except ImportError:
HAVE_SVGWRITE = False
def check_svgwrite_installed():
if not HAVE_SVGWRITE:
raise IOError(
"svg exporter not available because the svgwrite package is not installed. use $pip install svgwrite'"
)
##########################
# Step import and export #
##########################
def read_step_file(
filename: str, as_compound: bool = True, verbosity: bool = False
) -> Union[TopoDS_Shape, List[TopoDS_Shape]]:
"""Read a STEP file and return the contained shape(s).
Args:
filename: Path to the STEP file to read
as_compound: If True, combine multiple shapes into a single compound.
Defaults to True.
verbosity: If True, print detailed information during import.
Defaults to False.
Returns:
Either a single TopoDS_Shape (if as_compound=True or only one shape present)
or a list of TopoDS_Shape objects
Raises:
FileNotFoundError: If the specified file does not exist
AssertionError: If there are errors during STEP file reading or conversion
"""
if not os.path.isfile(filename):
raise FileNotFoundError(f"STEP file not found: {filename}")
step_reader = STEPControl_Reader()
status = step_reader.ReadFile(filename)
if status != IFSelect_RetDone:
raise AssertionError("Error: can't read file.")
if verbosity:
step_reader.PrintCheckLoad(False, IFSelect_ItemsByEntity)
step_reader.PrintCheckTransfer(False, IFSelect_ItemsByEntity)
transfer_result = step_reader.TransferRoots()
if not transfer_result:
raise AssertionError("Transfer failed.")
nb_shapes = step_reader.NbShapes()
if nb_shapes == 0:
raise AssertionError("No shape to transfer.")
if nb_shapes == 1:
if as_compound:
return step_reader.Shape(1)
return [step_reader.Shape(1)]
shapes = []
for i in range(1, nb_shapes + 1):
shape = step_reader.Shape(i)
if not shape.IsNull():
shapes.append(shape)
if as_compound:
compound = TopoDS_Compound()
builder = BRep_Builder()
builder.MakeCompound(compound)
for shape in shapes:
builder.Add(compound, shape)
return compound
return shapes
def write_step_file(
shape: TopoDS_Shape, filename: str, application_protocol: str = "AP203"
) -> None:
"""Export a shape to STEP format.
Args:
shape: The shape to export
filename: Target STEP file path
application_protocol: STEP format version to use.
Can be "AP203" (basic geometry), "AP214IS" (colors and layers),
or "AP242DIS" (latest version with PMI support).
Defaults to "AP203".
Raises:
AssertionError: If shape is null or protocol is invalid
IOError: If export fails
"""
if shape.IsNull():
raise AssertionError("Shape is null.")
if application_protocol not in ["AP203", "AP214IS", "AP242DIS"]:
raise AssertionError(
f"application_protocol must be either AP203 or AP214IS. You passed {application_protocol}."
)
if os.path.isfile(filename):
print(f"Warning: {filename} file already exists and will be replaced")
# Initialize STEP writer
writer = STEPControl_Writer()
Interface_Static.SetCVal("write.step.schema", application_protocol)
# Convert and write shape
writer.Transfer(shape, STEPControl_AsIs)
status = writer.Write(filename)
if status != IFSelect_RetDone:
raise IOError("Error while writing shape to STEP file.")
if not os.path.isfile(filename):
raise IOError(f"{filename} not saved to filesystem.")
def read_step_file_with_names_colors(
filename: str,
) -> Dict[TopoDS_Shape, List[Union[str, Quantity_Color]]]:
"""
Reads a STEP file and extracts shapes with their names and colors using OCAF.
This function processes a STEP file, including its assembly structure,
and returns a dictionary mapping each shape to its name and color.
:param filename: The path to the STEP file.
:return: A dictionary where keys are TopoDS_Shape objects and values are
lists containing the shape's name and its Quantity_Color.
:raises FileNotFoundError: If the specified file does not exist.
"""
if not os.path.isfile(filename):
raise FileNotFoundError(f"{filename} not found.")
# the list:
output_shapes = {}
# create an handle to a document
doc = TDocStd_Document("pythonocc-doc-step-import")
# Get root assembly
shape_tool = XCAFDoc_DocumentTool.ShapeTool(doc.Main())
color_tool = XCAFDoc_DocumentTool.ColorTool(doc.Main())
# layer_tool = XCAFDoc_DocumentTool_LayerTool(doc.Main())
# mat_tool = XCAFDoc_DocumentTool_MaterialTool(doc.Main())
step_reader = STEPCAFControl_Reader()
step_reader.SetColorMode(True)
step_reader.SetLayerMode(True)
step_reader.SetNameMode(True)
step_reader.SetMatMode(True)
step_reader.SetGDTMode(True)
status = step_reader.ReadFile(filename)
if status == IFSelect_RetDone:
step_reader.Transfer(doc)
locs = []
def _get_sub_shapes(lab, loc):
l_subss = TDF_LabelSequence()
shape_tool.GetSubShapes(lab, l_subss)
# print("Nb subshapes :", l_subss.Length())
l_comps = TDF_LabelSequence()
shape_tool.GetComponents(lab, l_comps)
name = lab.GetLabelName()
print("Name :", name)
if shape_tool.IsAssembly(lab):
l_c = TDF_LabelSequence()
shape_tool.GetComponents(lab, l_c)
for i in range(l_c.Length()):
label = l_c.Value(i + 1)
if shape_tool.IsReference(label):
# print("\n######## reference label :", label)
label_reference = TDF_Label()
shape_tool.GetReferredShape(label, label_reference)
loc = shape_tool.GetLocation(label)
locs.append(loc)
_get_sub_shapes(label_reference, loc)
locs.pop()
elif shape_tool.IsSimpleShape(lab):
# print("\n######## simpleshape label :", lab)
shape = shape_tool.GetShape(lab)
# print(" all ass locs :", locs)
loc = TopLoc_Location()
for location in locs:
loc = loc.Multiplied(location)
c = Quantity_Color(0.5, 0.5, 0.5, Quantity_TOC_RGB) # default color
color_set = False
if (
color_tool.GetInstanceColor(shape, 0, c)
or color_tool.GetInstanceColor(shape, 1, c)
or color_tool.GetInstanceColor(shape, 2, c)
):
color_tool.SetInstanceColor(shape, 0, c)
color_tool.SetInstanceColor(shape, 1, c)
color_tool.SetInstanceColor(shape, 2, c)
color_set = True
n = c.Name(c.Red(), c.Green(), c.Blue())
print(
" instance color Name & RGB: ",
c,
n,
c.Red(),
c.Green(),
c.Blue(),
)
if not color_set:
if (
XCAFDoc_ColorTool.GetColor(lab, 0, c)
or XCAFDoc_ColorTool.GetColor(lab, 1, c)
or XCAFDoc_ColorTool.GetColor(lab, 2, c)
):
color_tool.SetInstanceColor(shape, 0, c)
color_tool.SetInstanceColor(shape, 1, c)
color_tool.SetInstanceColor(shape, 2, c)
n = c.Name(c.Red(), c.Green(), c.Blue())
print(
" shape color Name & RGB: ",
c,
n,
c.Red(),
c.Green(),
c.Blue(),
)
shape_disp = BRepBuilderAPI_Transform(shape, loc.Transformation()).Shape()
if shape_disp not in output_shapes:
output_shapes[shape_disp] = [lab.GetLabelName(), c]
for i in range(l_subss.Length()):
lab_subs = l_subss.Value(i + 1)
# print("\n######## simpleshape subshape label :", lab)
shape_sub = shape_tool.GetShape(lab_subs)
c = Quantity_Color(0.5, 0.5, 0.5, Quantity_TOC_RGB) # default color
color_set = False
if (
color_tool.GetInstanceColor(shape_sub, 0, c)
or color_tool.GetInstanceColor(shape_sub, 1, c)
or color_tool.GetInstanceColor(shape_sub, 2, c)
):
color_tool.SetInstanceColor(shape_sub, 0, c)
color_tool.SetInstanceColor(shape_sub, 1, c)
color_tool.SetInstanceColor(shape_sub, 2, c)
color_set = True
n = c.Name(c.Red(), c.Green(), c.Blue())
print(
" instance color Name & RGB: ",
c,
n,
c.Red(),
c.Green(),
c.Blue(),
)
if not color_set:
if (
XCAFDoc_ColorTool.GetColor(lab_subs, 0, c)
or XCAFDoc_ColorTool.GetColor(lab_subs, 1, c)
or XCAFDoc_ColorTool.GetColor(lab_subs, 2, c)
):
color_tool.SetInstanceColor(shape, 0, c)
color_tool.SetInstanceColor(shape, 1, c)
color_tool.SetInstanceColor(shape, 2, c)
n = c.Name(c.Red(), c.Green(), c.Blue())
print(
" shape color Name & RGB: ",
c,
n,
c.Red(),
c.Green(),
c.Blue(),
)
shape_to_disp = BRepBuilderAPI_Transform(
shape_sub, loc.Transformation()
).Shape()
# position the subshape to display
if shape_to_disp not in output_shapes:
output_shapes[shape_to_disp] = [lab_subs.GetLabelName(), c]
def _get_shapes():
labels = TDF_LabelSequence()
shape_tool.GetFreeShapes(labels)
print("Number of shapes at root :", labels.Length())
for i in range(labels.Length()):
root_item = labels.Value(i + 1)
_get_sub_shapes(root_item, None)
_get_shapes()
return output_shapes
#########################
# STL import and export #
#########################
def write_stl_file(
shape: TopoDS_Shape,
filename: str,
mode: str = "ascii",
linear_deflection: float = 0.9,
angular_deflection: float = 0.5,
) -> None:
"""
Export a shape to STL format.
The shape is first meshed using the specified deflection parameters before export.
:param shape: The shape to export.
:param filename: Target STL file path.
:param mode: Export format, either "ascii" or "binary". Defaults to "ascii".
:param linear_deflection: Maximum distance between mesh and actual surface.
Lower values produce more accurate but larger meshes.
Defaults to 0.9.
:param angular_deflection: Maximum angle between mesh elements in radians.
Lower values produce smoother meshes.
Defaults to 0.5.
:raises AssertionError: If shape is null or meshing fails.
:raises IOError: If export fails.
"""
if shape.IsNull():
raise AssertionError("Shape is null.")
if mode not in ["ascii", "binary"]:
raise AssertionError("mode should be either ascii or binary")
if os.path.isfile(filename):
print(f"Warning: {filename} already exists and will be replaced")
# Mesh the shape
mesh = BRepMesh_IncrementalMesh(
shape, linear_deflection, False, angular_deflection, True
)
mesh.Perform()
if not mesh.IsDone():
raise AssertionError("Mesh is not done.")
# Export to STL
writer = StlAPI_Writer()
writer.SetASCIIMode(mode == "ascii")
writer.Write(shape, filename)
if not os.path.isfile(filename):
raise IOError("File not written to disk.")
def read_stl_file(
filename: str, sew_shape: bool = False, make_solid: bool = False
) -> TopoDS_Shape:
"""
Reads an STL file and returns a TopoDS_Shape.
:param filename: The path to the STL file.
:param sew_shape: sew all triangular faces after loading
:param make_solid: fill the surfacic mesh to return a TopoDS_Solid
:return: The shape read from the file.
:raises FileNotFoundError: If the specified file does not exist.
:raises AssertionError: If the shape in the file is null.
"""
if not os.path.isfile(filename):
raise FileNotFoundError(f"{filename} not found.")
if not sew_shape and make_solid:
raise AssertionError("Please enable sew_shape in order to make solid.")
the_shape = TopoDS_Shape()
stlapi.Read(the_shape, filename)
if the_shape.IsNull():
raise AssertionError("Shape is null.")
if sew_shape:
sewer = BRepBuilderAPI_Sewing()
sewer.Add(the_shape)
sewer.Perform()
sewed_shape = sewer.SewedShape()
if make_solid:
return BRepBuilderAPI_MakeSolid(sewed_shape).Shape()
# Return the sewed shape
return sewed_shape
return the_shape
######################
# IGES import/export #
######################
def read_iges_file(
filename: str,
return_as_shapes: bool = False,
verbosity: bool = False,
visible_only: bool = False,
) -> List[TopoDS_Shape]:
"""
Reads an IGES file and returns the shapes.
:param filename: The path to the IGES file.
:param return_as_shapes: If True, returns a list of shapes. Otherwise, returns
a single compound shape. Defaults to False.
:param verbosity: If True, prints detailed information during import.
Defaults to False.
:param visible_only: If True, only reads visible entities. Defaults to False.
:return: A list of shapes or a single compound shape.
:raises FileNotFoundError: If the specified file does not exist.
:raises IOError: If the file cannot be read.
"""
if not os.path.isfile(filename):
raise FileNotFoundError(f"{filename} not found.")
IGESControl_Controller.Init()
iges_reader = IGESControl_Reader()
iges_reader.SetReadVisible(visible_only)
status = iges_reader.ReadFile(filename)
if status != IFSelect_RetDone: # check status
raise IOError("Cannot read IGES file")
if verbosity:
failsonly = False
iges_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity)
iges_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity)
iges_reader.ClearShapes()
iges_reader.TransferRoots()
nbr = iges_reader.NbShapes()
_shapes = []
for i in range(1, nbr + 1):
a_shp = iges_reader.Shape(i)
if not a_shp.IsNull():
_shapes.append(a_shp)
# create a compound and store all shapes
if not return_as_shapes:
builder = BRep_Builder()
compound = TopoDS_Compound()
builder.MakeCompound(compound)
for s in _shapes:
builder.Add(compound, s)
return [compound]
return _shapes
def write_iges_file(a_shape: TopoDS_Shape, filename: str):
"""
Exports a shape to an IGES file.
:param a_shape: The TopoDS_Shape to export.
:param filename: The path to the output IGES file.
:raises AssertionError: If the shape is null or the export fails.
:raises IOError: If the file cannot be written to disk.
"""
# a few checks
if a_shape.IsNull():
raise AssertionError("Shape is null.")
if os.path.isfile(filename):
print(f"Warning: {filename} already exists and will be replaced")
# create and initialize the step exporter
iges_writer = IGESControl_Writer()
iges_writer.AddShape(a_shape)
status = iges_writer.Write(filename)
if status != IFSelect_RetDone:
raise AssertionError("Not done.")
if not os.path.isfile(filename):
raise IOError("File not written to disk.")
##############
# SVG export #
##############
def edge_to_svg_polyline(
topods_edge: TopoDS_Edge, tol: float = 0.1, unit: str = "mm"
) -> Tuple[Any, Bnd_Box2d]:
"""
Converts a TopoDS_Edge to an SVG polyline.
:param topods_edge: The edge to convert.
:param tol: The tolerance for discretization. Defaults to 0.1.
:param unit: The unit of the coordinates ('mm' or 'm'). Defaults to 'mm'.
:return: A tuple containing the svgwrite.shapes.Polyline and the 2D bounding box.
"""
check_svgwrite_installed()
unit_factor = 1 # by default
if unit == "mm":
unit_factor = 1
elif unit == "m":
unit_factor = 1e3
points_3d = discretize_edge(topods_edge, tol)
points_2d = []
box2d = Bnd_Box2d()
for point in points_3d:
# we tak only the first 2 coordinates (x and y, leave z)
x_p = -point[0] * unit_factor
y_p = point[1] * unit_factor
box2d.Add(gp_Pnt2d(x_p, y_p))
points_2d.append((x_p, y_p))
return svgwrite.shapes.Polyline(points_2d, fill="none"), box2d
def export_shape_to_svg(
shape: TopoDS_Shape,
filename: str = None,
width: int = 800,
height: int = 600,
margin_left: int = 10,
margin_top: int = 30,
export_hidden_edges: bool = True,
location: gp_Pnt = gp_Pnt(0, 0, 0),
direction: gp_Dir = gp_Dir(1, 1, 1),
color: str = "black",
line_width: str = "1px",
unit: str = "mm",
) -> Union[bool, str]:
"""
Exports a shape to an SVG file or string.
:param shape: The TopoDS_Shape to export.
:param filename: If provided, the path to save the SVG file.
:param width: The width of the SVG canvas in pixels.
:param height: The height of the SVG canvas in pixels.
:param margin_left: The left margin in pixels.
:param margin_top: The top margin in pixels.
:param export_hidden_edges: If True, hidden edges are drawn with a dashed line.
:param location: The viewpoint location for HLR.
:param direction: The view direction for HLR.
:param color: The color of the lines.
:param line_width: The width of the lines.
:param unit: The unit of the coordinates ('mm' or 'm').
:return: The SVG content as a string if no filename is provided, otherwise True.
:raises AssertionError: If the shape is null or the export fails.
"""
check_svgwrite_installed()
if shape.IsNull():
raise AssertionError("shape is Null")
# find all edges
visible_edges, hidden_edges = get_sorted_hlr_edges(
shape,
position=location,
direction=direction,
export_hidden_edges=export_hidden_edges,
)
# compute polylines for all edges
# we compute a global 2d bounding box as well, to be able to compute
# the scale factor and translation vector to apply to all 2d edges so that
# they fit the svg canva
global_2d_bounding_box = Bnd_Box2d()
polylines = []
for visible_edge in visible_edges:
visible_svg_line, visible_edge_box2d = edge_to_svg_polyline(
visible_edge, 0.1, unit
)
polylines.append(visible_svg_line)
global_2d_bounding_box.Add(visible_edge_box2d)
if export_hidden_edges:
for hidden_edge in hidden_edges:
hidden_svg_line, hidden_edge_box2d = edge_to_svg_polyline(
hidden_edge, 0.1, unit
)
# hidden lines are dashed style
hidden_svg_line.dasharray([5, 5])
polylines.append(hidden_svg_line)
global_2d_bounding_box.Add(hidden_edge_box2d)
# translate and scale polylines
# first compute shape translation and scale according to size/margins
x_min, y_min, x_max, y_max = global_2d_bounding_box.Get()
bb2d_width = x_max - x_min
bb2d_height = y_max - y_min
# build the svg drawing
dwg = svgwrite.Drawing(filename, (width, height), debug=True)
# adjust the view box so that the lines fit then svg canvas
dwg.viewbox(
x_min - margin_left,
y_min - margin_top,
bb2d_width + 2 * margin_left,
bb2d_height + 2 * margin_top,
)
for polyline in polylines:
# apply color and style
polyline.stroke(color, width=line_width, linecap="round")
# then adds the polyline to the svg canva
dwg.add(polyline)
# export to string or file according to the user choice
if filename is not None:
dwg.save()
if not os.path.isfile(filename):
raise AssertionError("svg export failed")
print(f"Shape successfully exported to {filename}")
return True
return dwg.tostring()
#################################################
# ply export (write not avaiable from upstream) #
#################################################
def write_ply_file(a_shape: TopoDS_Shape, ply_filename: str):
"""
Exports a shape to a PLY file using OCAF.
:param a_shape: The TopoDS_Shape to export.
:param ply_filename: The path to the output PLY file.
"""
# create a document
doc = TDocStd_Document("pythonocc-doc-ply-export")
shape_tool = XCAFDoc_DocumentTool.ShapeTool(doc.Main())
# mesh shape
breptools.Clean(a_shape)
msh_algo = BRepMesh_IncrementalMesh(a_shape, True)
msh_algo.Perform()
shape_tool.AddShape(a_shape)
# metadata
a_file_info = TColStd_IndexedDataMapOfStringString()
a_file_info.Add(
TCollection_AsciiString("Authors"), TCollection_AsciiString("pythonocc")
)
rwply_writer = RWPly_CafWriter(ply_filename)
rwply_writer.SetNormals(True)
rwply_writer.SetColors(True)
rwply_writer.SetTexCoords(True)
rwply_writer.SetPartId(True)
rwply_writer.SetFaceId(True)
rwply_writer.Perform(doc, a_file_info, Message_ProgressRange())
#################################################
# Obj export (write not avaiable from upstream) #
#################################################
def write_obj_file(a_shape: TopoDS_Shape, obj_filename: str):
"""
Exports a shape to an OBJ file using OCAF.
:param a_shape: The TopoDS_Shape to export.
:param obj_filename: The path to the output OBJ file.
"""
# create a document
doc = TDocStd_Document("pythonocc-doc-obj-export")
shape_tool = XCAFDoc_DocumentTool.ShapeTool(doc.Main())
# mesh shape
breptools.Clean(a_shape)
msh_algo = BRepMesh_IncrementalMesh(a_shape, True)
msh_algo.Perform()
shape_tool.AddShape(a_shape)
# metadata
a_file_info = TColStd_IndexedDataMapOfStringString()
a_file_info.Add(
TCollection_AsciiString("Authors"), TCollection_AsciiString("pythonocc")
)
rwobj_writer = RWObj_CafWriter(obj_filename)
# apply a scale factor of 0.001 to mimic conversion from m to mm
csc = rwobj_writer.ChangeCoordinateSystemConverter()
system_unit_factor = unitsmethods.GetCasCadeLengthUnit() * 0.001
csc.SetInputLengthUnit(system_unit_factor)
csc.SetOutputLengthUnit(system_unit_factor)
csc.SetInputCoordinateSystem(RWMesh_CoordinateSystem_posYfwd_posZup)
csc.SetOutputCoordinateSystem(RWMesh_CoordinateSystem_negZfwd_posYup)
rwobj_writer.SetCoordinateSystemConverter(csc)
rwobj_writer.Perform(doc, a_file_info, Message_ProgressRange())
########
# gltf #
########
def read_gltf_file(
filename: str,
is_parallel: bool = False,
is_double_precision: bool = False,
skip_late_data_loading: bool = False,
keep_late_data: bool = True,
verbose: bool = False,
load_all_scenes: bool = False,
) -> List[TopoDS_Shape]:
"""
Reads a glTF file and returns the shape.
:param filename: The path to the glTF file.
:param is_parallel: If True, uses parallel processing. Defaults to False.
:param is_double_precision: If True, uses double precision. Defaults to False.
:param skip_late_data_loading: If True, skips loading late data. Defaults to False.
:param keep_late_data: If True, keeps late data. Defaults to True.
:param verbose: If True, prints debug messages. Defaults to False.
:param load_all_scenes: If True, loads all scenes. Defaults to False.
:return: A list containing the read shape.
:raises FileNotFoundError: If the specified file does not exist.
:raises IOError: If the file cannot be read.
"""
if not os.path.isfile(filename):
raise FileNotFoundError(f"{filename} not found.")
gltf_reader = RWGltf_CafReader()
gltf_reader.SetSystemCoordinateSystem(RWMesh_CoordinateSystem_posYfwd_posZup)
gltf_reader.SetParallel(is_parallel)
gltf_reader.SetDoublePrecision(is_double_precision)
gltf_reader.SetToSkipLateDataLoading(skip_late_data_loading)
gltf_reader.SetToKeepLateData(keep_late_data)
gltf_reader.SetToPrintDebugMessages(verbose)
gltf_reader.SetLoadAllScenes(load_all_scenes)
status = gltf_reader.Perform(filename, Message_ProgressRange())
if status != IFSelect_RetDone:
raise IOError("Error while reading GLTF file.")
return [gltf_reader.SingleShape()]
def write_gltf_file(a_shape: TopoDS_Shape, gltf_filename: str, binary=True):
"""
Exports a shape to a glTF file using OCAF.
:param a_shape: The TopoDS_Shape to export.
:param gltf_filename: The path to the output glTF file.
:param binary: If True, exports to a binary glTF (.glb) file. Defaults to True.
:raises IOError: If the export fails.
"""
# create a document
doc = TDocStd_Document("pythonocc-doc-gltf-export")
shape_tool = XCAFDoc_DocumentTool.ShapeTool(doc.Main())
# mesh shape
breptools.Clean(a_shape)
msh_algo = BRepMesh_IncrementalMesh(a_shape, True)
msh_algo.Perform()
shape_tool.AddShape(a_shape)
# metadata
a_file_info = TColStd_IndexedDataMapOfStringString()
a_file_info.Add(
TCollection_AsciiString("Authors"), TCollection_AsciiString("pythonocc")
)
rwgltf_writer = RWGltf_CafWriter(gltf_filename, binary)
status = rwgltf_writer.Perform(doc, a_file_info, Message_ProgressRange())
if status != IFSelect_RetDone:
raise IOError("Error while writing shape to GLTF file.")