cad-to-dagmc 0.9.8__py3-none-any.whl → 0.10.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.
_version.py CHANGED
@@ -28,7 +28,7 @@ version_tuple: VERSION_TUPLE
28
28
  commit_id: COMMIT_ID
29
29
  __commit_id__: COMMIT_ID
30
30
 
31
- __version__ = version = '0.9.8'
32
- __version_tuple__ = version_tuple = (0, 9, 8)
31
+ __version__ = version = '0.10.0'
32
+ __version_tuple__ = version_tuple = (0, 10, 0)
33
33
 
34
34
  __commit_id__ = commit_id = None
cad_to_dagmc/__init__.py CHANGED
@@ -13,5 +13,4 @@ except PackageNotFoundError:
13
13
 
14
14
  __all__ = ["__version__"]
15
15
 
16
- from .direct_mesh_plugin import *
17
16
  from .core import *
cad_to_dagmc/core.py CHANGED
@@ -9,7 +9,7 @@ import tempfile
9
9
  import warnings
10
10
  from typing import Iterable
11
11
  from cad_to_dagmc import __version__
12
- from .direct_mesh_plugin import to_mesh
12
+ import cadquery_direct_mesh_plugin
13
13
 
14
14
 
15
15
  def define_moab_core_and_tags() -> tuple[core.Core, dict]:
@@ -89,7 +89,11 @@ def vertices_to_h5m(
89
89
  raise ValueError(msg)
90
90
 
91
91
  # limited attribute checking to see if user passed in a list of CadQuery vectors
92
- if hasattr(vertices[0], "x") and hasattr(vertices[0], "y") and hasattr(vertices[0], "z"):
92
+ if (
93
+ hasattr(vertices[0], "x")
94
+ and hasattr(vertices[0], "y")
95
+ and hasattr(vertices[0], "z")
96
+ ):
93
97
  vertices_floats = []
94
98
  for vert in vertices:
95
99
  vertices_floats.append((vert.x, vert.y, vert.z))
@@ -142,7 +146,9 @@ def vertices_to_h5m(
142
146
  if len(face_ids_with_solid_ids[face_id]) == 2:
143
147
  other_solid_id = face_ids_with_solid_ids[face_id][1]
144
148
  other_volume_set = volume_sets_by_solid_id[other_solid_id]
145
- sense_data = np.array([other_volume_set, volume_set], dtype="uint64")
149
+ sense_data = np.array(
150
+ [other_volume_set, volume_set], dtype="uint64"
151
+ )
146
152
  else:
147
153
  sense_data = np.array([volume_set, 0], dtype="uint64")
148
154
 
@@ -233,7 +239,9 @@ def get_volumes(gmsh, assembly, method="file", scale_factor=1.0):
233
239
 
234
240
  if scale_factor != 1.0:
235
241
  dim_tags = gmsh.model.getEntities(3)
236
- gmsh.model.occ.dilate(dim_tags, 0.0, 0.0, 0.0, scale_factor, scale_factor, scale_factor)
242
+ gmsh.model.occ.dilate(
243
+ dim_tags, 0.0, 0.0, 0.0, scale_factor, scale_factor, scale_factor
244
+ )
237
245
  # update the model to ensure the scaling factor has been applied
238
246
  gmsh.model.occ.synchronize()
239
247
 
@@ -298,7 +306,9 @@ def set_sizes_for_mesh(
298
306
  )
299
307
 
300
308
  # Step 1: Preprocess boundaries to find shared surfaces and decide mesh sizes
301
- boundary_sizes = {} # Dictionary to store the mesh size and count for each boundary
309
+ boundary_sizes = (
310
+ {}
311
+ ) # Dictionary to store the mesh size and count for each boundary
302
312
  for volume_id, size in set_size.items():
303
313
  boundaries = gmsh.model.getBoundary(
304
314
  [(3, volume_id)], recursive=True
@@ -373,7 +383,8 @@ def mesh_to_vertices_and_triangles(
373
383
  for nodeTag in nodeTags:
374
384
  shifted_node_tags.append(nodeTag - 1)
375
385
  grouped_node_tags = [
376
- shifted_node_tags[i : i + n] for i in range(0, len(shifted_node_tags), n)
386
+ shifted_node_tags[i : i + n]
387
+ for i in range(0, len(shifted_node_tags), n)
377
388
  ]
378
389
  nodes_in_each_surface[surface] = grouped_node_tags
379
390
  triangles_by_solid_by_face[vol_id] = nodes_in_each_surface
@@ -583,14 +594,18 @@ class CadToDagmc:
583
594
  scaled_part = part
584
595
  else:
585
596
  scaled_part = part.scale(scale_factor)
586
- return self.add_cadquery_object(cadquery_object=scaled_part, material_tags=material_tags)
597
+ return self.add_cadquery_object(
598
+ cadquery_object=scaled_part, material_tags=material_tags
599
+ )
587
600
 
588
601
  def add_cadquery_object(
589
602
  self,
590
603
  cadquery_object: (
591
- cq.assembly.Assembly | cq.occ_impl.shapes.Compound | cq.occ_impl.shapes.Solid
604
+ cq.assembly.Assembly
605
+ | cq.occ_impl.shapes.Compound
606
+ | cq.occ_impl.shapes.Solid
592
607
  ),
593
- material_tags: list[str] | None,
608
+ material_tags: list[str] | str,
594
609
  scale_factor: float = 1.0,
595
610
  ) -> int:
596
611
  """Loads the parts from CadQuery object into the model.
@@ -612,18 +627,53 @@ class CadToDagmc:
612
627
  int: number of volumes in the stp file.
613
628
  """
614
629
 
630
+ if isinstance(material_tags, str) and material_tags not in [
631
+ "assembly_materials",
632
+ "assembly_names",
633
+ ]:
634
+ raise ValueError(
635
+ f"If material_tags is a string it must be 'assembly_materials' or 'assembly_names' but got {material_tags}"
636
+ )
637
+
615
638
  if isinstance(cadquery_object, cq.assembly.Assembly):
616
- cadquery_object = cadquery_object.toCompound()
639
+ # look for materials in each part of the assembly
640
+ if material_tags == "assembly_materials":
641
+ material_tags = []
642
+ for child in _get_all_leaf_children(cadquery_object):
643
+ if child.material is not None and child.material.name is not None:
644
+ material_tags.append(str(child.material.name))
645
+ else:
646
+ raise ValueError(
647
+ f"Not all parts in the assembly have materials assigned.\n"
648
+ f"When adding to an assembly include material=cadquery.Material('material_name')\n"
649
+ f"Missing material tag for child: {child}.\n"
650
+ "Please assign material tags to all parts or provide material_tags argument when adding the assembly.\n"
651
+ )
652
+ print("material_tags found from assembly materials:", material_tags)
653
+ elif material_tags == "assembly_names":
654
+ material_tags = []
655
+ for child in _get_all_leaf_children(cadquery_object):
656
+ # parts always have a name as cq will auto assign one
657
+ material_tags.append(child.name)
658
+ print("material_tags found from assembly names:", material_tags)
659
+
660
+ cadquery_compound = cadquery_object.toCompound()
661
+ else:
662
+ cadquery_compound = cadquery_object
617
663
 
618
- if isinstance(cadquery_object, (cq.occ_impl.shapes.Compound, cq.occ_impl.shapes.Solid)):
619
- iterable_solids = cadquery_object.Solids()
664
+ if isinstance(
665
+ cadquery_compound, (cq.occ_impl.shapes.Compound, cq.occ_impl.shapes.Solid)
666
+ ):
667
+ iterable_solids = cadquery_compound.Solids()
620
668
  else:
621
- iterable_solids = cadquery_object.val().Solids()
669
+ iterable_solids = cadquery_compound.val().Solids()
622
670
 
623
671
  if scale_factor == 1.0:
624
672
  scaled_iterable_solids = iterable_solids
625
673
  else:
626
- scaled_iterable_solids = [part.scale(scale_factor) for part in iterable_solids]
674
+ scaled_iterable_solids = [
675
+ part.scale(scale_factor) for part in iterable_solids
676
+ ]
627
677
 
628
678
  check_material_tags(material_tags, scaled_iterable_solids)
629
679
  if material_tags:
@@ -724,7 +774,9 @@ class CadToDagmc:
724
774
  gmsh.model.occ.synchronize()
725
775
  # Clear the mesh
726
776
  gmsh.model.mesh.clear()
727
- gmsh.option.setNumber("Mesh.SaveElementTagType", 3) # Save only volume elements
777
+ gmsh.option.setNumber(
778
+ "Mesh.SaveElementTagType", 3
779
+ ) # Save only volume elements
728
780
 
729
781
  gmsh.model.mesh.generate(3)
730
782
 
@@ -795,7 +847,9 @@ class CadToDagmc:
795
847
 
796
848
  gmsh = init_gmsh()
797
849
 
798
- gmsh, _ = get_volumes(gmsh, imprinted_assembly, method=method, scale_factor=scale_factor)
850
+ gmsh, _ = get_volumes(
851
+ gmsh, imprinted_assembly, method=method, scale_factor=scale_factor
852
+ )
799
853
 
800
854
  gmsh = set_sizes_for_mesh(
801
855
  gmsh=gmsh,
@@ -996,8 +1050,7 @@ class CadToDagmc:
996
1050
  if meshing_backend == "cadquery":
997
1051
 
998
1052
  # Mesh the assembly using CadQuery's direct-mesh plugin
999
- cq_mesh = to_mesh(
1000
- assembly,
1053
+ cq_mesh = assembly.toMesh(
1001
1054
  imprint=imprint,
1002
1055
  tolerance=tolerance,
1003
1056
  angular_tolerance=angular_tolerance,
@@ -1006,9 +1059,13 @@ class CadToDagmc:
1006
1059
 
1007
1060
  # Fix the material tag order for imprinted assemblies
1008
1061
  if cq_mesh["imprinted_assembly"] is not None:
1009
- imprinted_solids_with_org_id = cq_mesh["imprinted_solids_with_orginal_ids"]
1062
+ imprinted_solids_with_org_id = cq_mesh[
1063
+ "imprinted_solids_with_orginal_ids"
1064
+ ]
1010
1065
 
1011
- scrambled_ids = get_ids_from_imprinted_assembly(imprinted_solids_with_org_id)
1066
+ scrambled_ids = get_ids_from_imprinted_assembly(
1067
+ imprinted_solids_with_org_id
1068
+ )
1012
1069
 
1013
1070
  material_tags_in_brep_order = order_material_ids_by_brep_order(
1014
1071
  original_ids, scrambled_ids, self.material_tags
@@ -1026,11 +1083,13 @@ class CadToDagmc:
1026
1083
  # If assembly is not to be imprinted, pass through the assembly as-is
1027
1084
  if imprint:
1028
1085
  print("Imprinting assembly for mesh generation")
1029
- imprinted_assembly, imprinted_solids_with_org_id = cq.occ_impl.assembly.imprint(
1030
- assembly
1086
+ imprinted_assembly, imprinted_solids_with_org_id = (
1087
+ cq.occ_impl.assembly.imprint(assembly)
1031
1088
  )
1032
1089
 
1033
- scrambled_ids = get_ids_from_imprinted_assembly(imprinted_solids_with_org_id)
1090
+ scrambled_ids = get_ids_from_imprinted_assembly(
1091
+ imprinted_solids_with_org_id
1092
+ )
1034
1093
 
1035
1094
  material_tags_in_brep_order = order_material_ids_by_brep_order(
1036
1095
  original_ids, scrambled_ids, self.material_tags
@@ -1090,7 +1149,9 @@ class CadToDagmc:
1090
1149
  gmsh.model.removePhysicalGroups([entry])
1091
1150
 
1092
1151
  gmsh.model.mesh.generate(3)
1093
- gmsh.option.setNumber("Mesh.SaveElementTagType", 3) # Save only volume elements
1152
+ gmsh.option.setNumber(
1153
+ "Mesh.SaveElementTagType", 3
1154
+ ) # Save only volume elements
1094
1155
  gmsh.write(umesh_filename)
1095
1156
 
1096
1157
  gmsh.finalize()
@@ -1098,3 +1159,13 @@ class CadToDagmc:
1098
1159
  return dagmc_filename, umesh_filename
1099
1160
  else:
1100
1161
  return dagmc_filename
1162
+
1163
+
1164
+ def _get_all_leaf_children(assembly):
1165
+ """Recursively yield all leaf children (parts, not assemblies) from a CadQuery assembly."""
1166
+ for child in assembly.children:
1167
+ # If the child is itself an assembly, recurse
1168
+ if hasattr(child, "children") and len(child.children) > 0:
1169
+ yield from _get_all_leaf_children(child)
1170
+ else:
1171
+ yield child
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cad_to_dagmc
3
- Version: 0.9.8
3
+ Version: 0.10.0
4
4
  Summary: Converts CAD files to a DAGMC h5m file
5
5
  Author-email: Jonathan Shimwell <mail@jshimwell.com>
6
6
  Project-URL: Homepage, https://github.com/fusion-energy/cad_to_dagmc
@@ -14,9 +14,10 @@ Description-Content-Type: text/markdown
14
14
  License-File: LICENSE
15
15
  Requires-Dist: trimesh
16
16
  Requires-Dist: networkx
17
- Requires-Dist: cadquery>=2.5.2
17
+ Requires-Dist: cadquery>=2.6.0
18
18
  Requires-Dist: numpy
19
19
  Requires-Dist: gmsh
20
+ Requires-Dist: cadquery_direct_mesh_plugin>=0.1.0
20
21
  Provides-Extra: tests
21
22
  Requires-Dist: pytest; extra == "tests"
22
23
  Requires-Dist: vtk; extra == "tests"
@@ -0,0 +1,8 @@
1
+ _version.py,sha256=XS8OMho0YiZyQ_qDeRsy__m_nWUzYVEJw-NLk1VtDQU,706
2
+ cad_to_dagmc/__init__.py,sha256=fskHUTyCunSpnpJUvBfAYjx4uwDKXHTTiMP6GqnFRf0,494
3
+ cad_to_dagmc/core.py,sha256=x4v7EeyXKBqsdcZeq_ks3EQ82yuteedAq8NA76rgJag,45732
4
+ cad_to_dagmc-0.10.0.dist-info/licenses/LICENSE,sha256=B8kznH_777JVNZ3HOKDc4Tj24F7wJ68ledaNYeL9sCw,1070
5
+ cad_to_dagmc-0.10.0.dist-info/METADATA,sha256=ZiH6QhnM8Dibqn72qAcMu_RzGyqOxyRKDW997dRkuHc,9045
6
+ cad_to_dagmc-0.10.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
7
+ cad_to_dagmc-0.10.0.dist-info/top_level.txt,sha256=zTi8C64SEBsE5WOtPovnxhOzt-E6Oc5nC3RW6M_5aEA,22
8
+ cad_to_dagmc-0.10.0.dist-info/RECORD,,
@@ -1,510 +0,0 @@
1
- # This is a temporary solution until we have to_mesh like functionality in a
2
- # PYPI distributed version of CadQuery.
3
- # This code is adapted from the cadquery-direct-mesh-plugin repository:
4
- # https://github.com/jmwright/cadquery-direct-mesh-plugin
5
-
6
- # Apache License
7
- # Version 2.0, January 2004
8
- # http://www.apache.org/licenses/
9
-
10
- # TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
11
-
12
- # 1. Definitions.
13
-
14
- # "License" shall mean the terms and conditions for use, reproduction,
15
- # and distribution as defined by Sections 1 through 9 of this document.
16
-
17
- # "Licensor" shall mean the copyright owner or entity authorized by
18
- # the copyright owner that is granting the License.
19
-
20
- # "Legal Entity" shall mean the union of the acting entity and all
21
- # other entities that control, are controlled by, or are under common
22
- # control with that entity. For the purposes of this definition,
23
- # "control" means (i) the power, direct or indirect, to cause the
24
- # direction or management of such entity, whether by contract or
25
- # otherwise, or (ii) ownership of fifty percent (50%) or more of the
26
- # outstanding shares, or (iii) beneficial ownership of such entity.
27
-
28
- # "You" (or "Your") shall mean an individual or Legal Entity
29
- # exercising permissions granted by this License.
30
-
31
- # "Source" form shall mean the preferred form for making modifications,
32
- # including but not limited to software source code, documentation
33
- # source, and configuration files.
34
-
35
- # "Object" form shall mean any form resulting from mechanical
36
- # transformation or translation of a Source form, including but
37
- # not limited to compiled object code, generated documentation,
38
- # and conversions to other media types.
39
-
40
- # "Work" shall mean the work of authorship, whether in Source or
41
- # Object form, made available under the License, as indicated by a
42
- # copyright notice that is included in or attached to the work
43
- # (an example is provided in the Appendix below).
44
-
45
- # "Derivative Works" shall mean any work, whether in Source or Object
46
- # form, that is based on (or derived from) the Work and for which the
47
- # editorial revisions, annotations, elaborations, or other modifications
48
- # represent, as a whole, an original work of authorship. For the purposes
49
- # of this License, Derivative Works shall not include works that remain
50
- # separable from, or merely link (or bind by name) to the interfaces of,
51
- # the Work and Derivative Works thereof.
52
-
53
- # "Contribution" shall mean any work of authorship, including
54
- # the original version of the Work and any modifications or additions
55
- # to that Work or Derivative Works thereof, that is intentionally
56
- # submitted to Licensor for inclusion in the Work by the copyright owner
57
- # or by an individual or Legal Entity authorized to submit on behalf of
58
- # the copyright owner. For the purposes of this definition, "submitted"
59
- # means any form of electronic, verbal, or written communication sent
60
- # to the Licensor or its representatives, including but not limited to
61
- # communication on electronic mailing lists, source code control systems,
62
- # and issue tracking systems that are managed by, or on behalf of, the
63
- # Licensor for the purpose of discussing and improving the Work, but
64
- # excluding communication that is conspicuously marked or otherwise
65
- # designated in writing by the copyright owner as "Not a Contribution."
66
-
67
- # "Contributor" shall mean Licensor and any individual or Legal Entity
68
- # on behalf of whom a Contribution has been received by Licensor and
69
- # subsequently incorporated within the Work.
70
-
71
- # 2. Grant of Copyright License. Subject to the terms and conditions of
72
- # this License, each Contributor hereby grants to You a perpetual,
73
- # worldwide, non-exclusive, no-charge, royalty-free, irrevocable
74
- # copyright license to reproduce, prepare Derivative Works of,
75
- # publicly display, publicly perform, sublicense, and distribute the
76
- # Work and such Derivative Works in Source or Object form.
77
-
78
- # 3. Grant of Patent License. Subject to the terms and conditions of
79
- # this License, each Contributor hereby grants to You a perpetual,
80
- # worldwide, non-exclusive, no-charge, royalty-free, irrevocable
81
- # (except as stated in this section) patent license to make, have made,
82
- # use, offer to sell, sell, import, and otherwise transfer the Work,
83
- # where such license applies only to those patent claims licensable
84
- # by such Contributor that are necessarily infringed by their
85
- # Contribution(s) alone or by combination of their Contribution(s)
86
- # with the Work to which such Contribution(s) was submitted. If You
87
- # institute patent litigation against any entity (including a
88
- # cross-claim or counterclaim in a lawsuit) alleging that the Work
89
- # or a Contribution incorporated within the Work constitutes direct
90
- # or contributory patent infringement, then any patent licenses
91
- # granted to You under this License for that Work shall terminate
92
- # as of the date such litigation is filed.
93
-
94
- # 4. Redistribution. You may reproduce and distribute copies of the
95
- # Work or Derivative Works thereof in any medium, with or without
96
- # modifications, and in Source or Object form, provided that You
97
- # meet the following conditions:
98
-
99
- # (a) You must give any other recipients of the Work or
100
- # Derivative Works a copy of this License; and
101
-
102
- # (b) You must cause any modified files to carry prominent notices
103
- # stating that You changed the files; and
104
-
105
- # (c) You must retain, in the Source form of any Derivative Works
106
- # that You distribute, all copyright, patent, trademark, and
107
- # attribution notices from the Source form of the Work,
108
- # excluding those notices that do not pertain to any part of
109
- # the Derivative Works; and
110
-
111
- # (d) If the Work includes a "NOTICE" text file as part of its
112
- # distribution, then any Derivative Works that You distribute must
113
- # include a readable copy of the attribution notices contained
114
- # within such NOTICE file, excluding those notices that do not
115
- # pertain to any part of the Derivative Works, in at least one
116
- # of the following places: within a NOTICE text file distributed
117
- # as part of the Derivative Works; within the Source form or
118
- # documentation, if provided along with the Derivative Works; or,
119
- # within a display generated by the Derivative Works, if and
120
- # wherever such third-party notices normally appear. The contents
121
- # of the NOTICE file are for informational purposes only and
122
- # do not modify the License. You may add Your own attribution
123
- # notices within Derivative Works that You distribute, alongside
124
- # or as an addendum to the NOTICE text from the Work, provided
125
- # that such additional attribution notices cannot be construed
126
- # as modifying the License.
127
-
128
- # You may add Your own copyright statement to Your modifications and
129
- # may provide additional or different license terms and conditions
130
- # for use, reproduction, or distribution of Your modifications, or
131
- # for any such Derivative Works as a whole, provided Your use,
132
- # reproduction, and distribution of the Work otherwise complies with
133
- # the conditions stated in this License.
134
-
135
- # 5. Submission of Contributions. Unless You explicitly state otherwise,
136
- # any Contribution intentionally submitted for inclusion in the Work
137
- # by You to the Licensor shall be under the terms and conditions of
138
- # this License, without any additional terms or conditions.
139
- # Notwithstanding the above, nothing herein shall supersede or modify
140
- # the terms of any separate license agreement you may have executed
141
- # with Licensor regarding such Contributions.
142
-
143
- # 6. Trademarks. This License does not grant permission to use the trade
144
- # names, trademarks, service marks, or product names of the Licensor,
145
- # except as required for reasonable and customary use in describing the
146
- # origin of the Work and reproducing the content of the NOTICE file.
147
-
148
- # 7. Disclaimer of Warranty. Unless required by applicable law or
149
- # agreed to in writing, Licensor provides the Work (and each
150
- # Contributor provides its Contributions) on an "AS IS" BASIS,
151
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
152
- # implied, including, without limitation, any warranties or conditions
153
- # of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
154
- # PARTICULAR PURPOSE. You are solely responsible for determining the
155
- # appropriateness of using or redistributing the Work and assume any
156
- # risks associated with Your exercise of permissions under this License.
157
-
158
- # 8. Limitation of Liability. In no event and under no legal theory,
159
- # whether in tort (including negligence), contract, or otherwise,
160
- # unless required by applicable law (such as deliberate and grossly
161
- # negligent acts) or agreed to in writing, shall any Contributor be
162
- # liable to You for damages, including any direct, indirect, special,
163
- # incidental, or consequential damages of any character arising as a
164
- # result of this License or out of the use or inability to use the
165
- # Work (including but not limited to damages for loss of goodwill,
166
- # work stoppage, computer failure or malfunction, or any and all
167
- # other commercial damages or losses), even if such Contributor
168
- # has been advised of the possibility of such damages.
169
-
170
- # 9. Accepting Warranty or Additional Liability. While redistributing
171
- # the Work or Derivative Works thereof, You may choose to offer,
172
- # and charge a fee for, acceptance of support, warranty, indemnity,
173
- # or other liability obligations and/or rights consistent with this
174
- # License. However, in accepting such obligations, You may act only
175
- # on Your own behalf and on Your sole responsibility, not on behalf
176
- # of any other Contributor, and only if You agree to indemnify,
177
- # defend, and hold each Contributor harmless for any liability
178
- # incurred by, or claims asserted against, such Contributor by reason
179
- # of your accepting any such warranty or additional liability.
180
-
181
- # END OF TERMS AND CONDITIONS
182
-
183
- # APPENDIX: How to apply the Apache License to your work.
184
-
185
- # To apply the Apache License to your work, attach the following
186
- # boilerplate notice, with the fields enclosed by brackets "[]"
187
- # replaced with your own identifying information. (Don't include
188
- # the brackets!) The text should be enclosed in the appropriate
189
- # comment syntax for the file format. We also recommend that a
190
- # file or class name and description of purpose be included on the
191
- # same "printed page" as the copyright notice for easier
192
- # identification within third-party archives.
193
-
194
- # Copyright [yyyy] [name of copyright owner]
195
-
196
- # Licensed under the Apache License, Version 2.0 (the "License");
197
- # you may not use this file except in compliance with the License.
198
- # You may obtain a copy of the License at
199
-
200
- # http://www.apache.org/licenses/LICENSE-2.0
201
-
202
- # Unless required by applicable law or agreed to in writing, software
203
- # distributed under the License is distributed on an "AS IS" BASIS,
204
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
205
- # See the License for the specific language governing permissions and
206
- # limitations under the License.
207
-
208
-
209
- from OCP.TopLoc import TopLoc_Location
210
- from OCP.BRep import BRep_Tool
211
- from OCP.BRepMesh import BRepMesh_IncrementalMesh
212
- from OCP import GCPnts, BRepAdaptor
213
- from OCP.TopAbs import TopAbs_REVERSED, TopAbs_IN
214
- from OCP.gp import gp_Pnt, gp_Vec
215
- import cadquery as cq
216
-
217
-
218
- def _is_interior_face(face, solid, tolerance=0.01):
219
- """
220
- Determine if a face is interior to a solid (like a cavity wall).
221
-
222
- This is more robust than just checking face orientation, as it considers
223
- the geometric relationship between the face and the solid.
224
- """
225
- # Get geometric surface and parameter bounds
226
- surf = BRep_Tool.Surface_s(face.wrapped)
227
- u_min, u_max, v_min, v_max = face._uvBounds()
228
-
229
- # # Take center point in UV space on the face
230
- u = (u_min + u_max) * 0.5
231
- v = (v_min + v_max) * 0.5
232
- face_pnt = surf.Value(u, v)
233
-
234
- # Determine if the face is most likely inside the solid
235
- is_inside = solid.isInside((face_pnt.X(), face_pnt.Y(), face_pnt.Z()))
236
-
237
- # Determine if the normal of the face points generally towards to the center of the solid
238
- is_pointing_inward = False
239
- face_normal = face.normalAt((face_pnt.X(), face_pnt.Y(), face_pnt.Z()))
240
- solid_center = solid.Center()
241
-
242
- to_center = gp_Vec(face_pnt, gp_Pnt(solid_center.x, solid_center.y, solid_center.z))
243
-
244
- # Dot product: negative = toward, positive = away
245
- dot = face_normal.dot(cq.Vector(to_center.Normalized()))
246
-
247
- if dot < 0:
248
- is_pointing_inward = False
249
- else:
250
- is_pointing_inward = True
251
-
252
- # If the face seems to be inside the solid and its normal points inwards, it should be an internal face
253
- is_internal_face = False
254
- if is_inside and is_pointing_inward:
255
- is_internal_face = True
256
-
257
- return is_internal_face
258
-
259
-
260
- def to_mesh(
261
- assembly,
262
- imprint=True,
263
- tolerance=0.1,
264
- angular_tolerance=0.1,
265
- scale_factor=1.0,
266
- include_brep_edges=False,
267
- include_brep_vertices=False,
268
- ):
269
- """
270
- Converts an assembly to a custom mesh format defined by the CadQuery team.
271
-
272
- :param imprint: Whether or not the assembly should be imprinted
273
- :param tolerance: Tessellation tolerance for mesh generation
274
- :param angular_tolerance: Angular tolerance for tessellation
275
- :param include_brep_edges: Whether to include BRep edge segments
276
- :param include_brep_vertices: Whether to include BRep vertices
277
- """
278
-
279
- # To keep track of the vertices and triangles in the mesh
280
- vertices = []
281
- vertex_map = {}
282
- solids = []
283
- solid_face_triangle = {}
284
- imprinted_assembly = None
285
- imprinted_solids_with_orginal_ids = None
286
- solid_colors = []
287
- solid_locs = []
288
- solid_brep_edge_segments = []
289
- solid_brep_vertices = []
290
-
291
- # Imprinted assemblies end up being compounds, whereas you have to step through each of the
292
- # parts in an assembly and extract the solids.
293
- if imprint:
294
- print("Imprinting assembly for mesh generation")
295
- # Imprint the assembly and process it as a compound
296
- (
297
- imprinted_assembly,
298
- imprinted_solids_with_orginal_ids,
299
- ) = cq.occ_impl.assembly.imprint(assembly)
300
-
301
- # Extract the solids from the imprinted assembly because we should not mesh the compound
302
- for solid in imprinted_assembly.Solids():
303
- solids.append(solid)
304
-
305
- # Keep track of the colors and location of each of the solids
306
- solid_colors.append((0.5, 0.5, 0.5, 1.0))
307
- solid_locs.append(cq.Location())
308
- else:
309
- # Step through every child in the assembly and save their solids
310
- for child in assembly.children:
311
- # Make sure we end up with a base shape
312
- obj = child.obj
313
- if type(child.obj).__name__ == "Workplane":
314
- solids.append(obj.val())
315
- else:
316
- solids.append(obj)
317
-
318
- # Use the color set for the assembly component, or use a default color
319
- if child.color:
320
- solid_colors.append(child.color.toTuple())
321
- else:
322
- solid_colors.append((0.5, 0.5, 0.5, 1.0))
323
-
324
- # Keep track of the location of each of the solids
325
- solid_locs.append(child.loc)
326
-
327
- # Solid and face IDs need to be unique unless they are a shared face
328
- solid_idx = 1 # We start at 1 to mimic gmsh
329
- face_idx = 1 # We start at id of 1 to mimic gmsh
330
-
331
- # Step through all of the collected solids and their respective faces to get the vertices
332
- for solid in solids:
333
- print(f"Meshing solid {solid_idx} of {len(solids)}")
334
- # Reset this each time so that we get the correct number of faces per solid
335
- face_triangles = {}
336
-
337
- # Order the faces in order of area, largest first
338
- sorted_faces = []
339
- face_areas = []
340
- for face in solid.Faces():
341
- area = face.Area()
342
- sorted_faces.append((face, area))
343
- face_areas.append(area)
344
-
345
- # Sort by area (largest first)
346
- sorted_faces.sort(key=lambda x: x[1], reverse=False)
347
-
348
- # Extract just the sorted faces if you need them separately
349
- sorted_face_list = [face_info[0] for face_info in sorted_faces]
350
-
351
- # Walk through all the faces
352
- for face in sorted_face_list:
353
- # Figure out if the face has a reversed orientation so we can handle the triangles accordingly
354
- is_reversed = False
355
- if face.wrapped.Orientation() == TopAbs_REVERSED:
356
- is_reversed = True
357
-
358
- # Location information of the face to place the vertices and edges correctly
359
- loc = TopLoc_Location()
360
-
361
- # Perform the tessellation
362
- BRepMesh_IncrementalMesh(face.wrapped, tolerance, False, angular_tolerance)
363
- face_mesh = BRep_Tool.Triangulation_s(face.wrapped, loc)
364
-
365
- # If this is not an imprinted assembly, override the location of the triangulation
366
- if not imprint:
367
- loc = solid_locs[solid_idx - 1].wrapped
368
-
369
- # Save the transformation so that we can place vertices in the correct locations later
370
- Trsf = loc.Transformation()
371
-
372
- # Pre-process all vertices from the face mesh for better performance
373
- face_vertices = {} # Map from face mesh node index to global vertex index
374
- for node_idx in range(1, face_mesh.NbNodes() + 1):
375
- node = face_mesh.Node(node_idx)
376
- v_trsf = node.Transformed(Trsf)
377
- vertex_coords = (
378
- v_trsf.X() * scale_factor,
379
- v_trsf.Y() * scale_factor,
380
- v_trsf.Z() * scale_factor,
381
- )
382
-
383
- # Use dictionary for O(1) lookup instead of O(n) list operations
384
- if vertex_coords in vertex_map:
385
- face_vertices[node_idx] = vertex_map[vertex_coords]
386
- else:
387
- global_vertex_idx = len(vertices)
388
- vertices.append(vertex_coords)
389
- vertex_map[vertex_coords] = global_vertex_idx
390
- face_vertices[node_idx] = global_vertex_idx
391
-
392
- # Step through the triangles of the face
393
- cur_triangles = []
394
- for i in range(1, face_mesh.NbTriangles() + 1):
395
- # Get the current triangle and its index vertices
396
- cur_tri = face_mesh.Triangle(i)
397
- idx_1, idx_2, idx_3 = cur_tri.Get()
398
-
399
- # Look up pre-processed vertex indices - O(1) operation
400
- if is_reversed:
401
- triangle_vertex_indices = [
402
- face_vertices[idx_1],
403
- face_vertices[idx_3],
404
- face_vertices[idx_2],
405
- ]
406
- else:
407
- triangle_vertex_indices = [
408
- face_vertices[idx_1],
409
- face_vertices[idx_2],
410
- face_vertices[idx_3],
411
- ]
412
-
413
- cur_triangles.append(triangle_vertex_indices)
414
-
415
- # Save this triangle for the current face
416
- face_triangles[face_idx] = cur_triangles
417
-
418
- # Move to the next face
419
- face_idx += 1
420
-
421
- solid_face_triangle[solid_idx] = face_triangles
422
-
423
- # If the caller wants to track edges, include them
424
- if include_brep_edges:
425
- # If this is not an imprinted assembly, override the location of the edges
426
- loc = TopLoc_Location()
427
- if not imprint:
428
- loc = solid_locs[solid_idx - 1].wrapped
429
-
430
- # Save the transformation so that we can place vertices in the correct locations later
431
- Trsf = loc.Transformation()
432
-
433
- # Add CadQuery-reported edges
434
- current_segments = []
435
- for edge in solid.edges():
436
- # We need to handle different kinds of edges differently
437
- gt = edge.geomType()
438
-
439
- # Line edges are just point to point
440
- if gt == "LINE":
441
- start = edge.startPoint().toPnt()
442
- end = edge.endPoint().toPnt()
443
-
444
- # Apply the assembly location transformation to each vertex
445
- start_trsf = start.Transformed(Trsf)
446
- located_start = (start_trsf.X(), start_trsf.Y(), start_trsf.Z())
447
- end_trsf = end.Transformed(Trsf)
448
- located_end = (end_trsf.X(), end_trsf.Y(), end_trsf.Z())
449
-
450
- # Save the start and end points for the edge
451
- current_segments.append([located_start, located_end])
452
- # If dealing with some sort of arc, discretize it into individual lines
453
- elif gt in ("CIRCLE", "ARC", "SPLINE", "BSPLINE", "ELLIPSE"):
454
- # Discretize the curve
455
- disc = GCPnts.GCPnts_TangentialDeflection(
456
- BRepAdaptor.BRepAdaptor_Curve(edge.wrapped),
457
- tolerance,
458
- angular_tolerance,
459
- )
460
-
461
- # Add each of the discretized sections to the edge list
462
- if disc.NbPoints() > 1:
463
- for i in range(2, disc.NbPoints() + 1):
464
- p_0 = disc.Value(i - 1)
465
- p_1 = disc.Value(i)
466
-
467
- # Apply the assembly location transformation to each vertex
468
- p_0_trsf = p_0.Transformed(Trsf)
469
- located_p_0 = (p_0_trsf.X(), p_0_trsf.Y(), p_0_trsf.Z())
470
- p_1_trsf = p_1.Transformed(Trsf)
471
- located_p_1 = (p_1_trsf.X(), p_1_trsf.Y(), p_1_trsf.Z())
472
-
473
- # Save the start and end points for the edge
474
- current_segments.append([located_p_0, located_p_1])
475
-
476
- solid_brep_edge_segments.append(current_segments)
477
-
478
- # Add CadQuery-reported vertices, if requested
479
- if include_brep_vertices:
480
- # If this is not an imprinted assembly, override the location of the edges
481
- loc = TopLoc_Location()
482
- if not imprint:
483
- loc = solid_locs[solid_idx - 1].wrapped
484
-
485
- # Save the transformation so that we can place vertices in the correct locations later
486
- Trsf = loc.Transformation()
487
-
488
- current_vertices = []
489
- for vertex in solid.vertices():
490
- p = BRep_Tool.Pnt_s(vertex.wrapped)
491
-
492
- # Apply the assembly location transformation to each vertex
493
- p_trsf = p.Transformed(Trsf)
494
- located_p = (p_trsf.X(), p_trsf.Y(), p_trsf.Z())
495
- current_vertices.append(located_p)
496
-
497
- solid_brep_vertices.append(current_vertices)
498
-
499
- # Move to the next solid
500
- solid_idx += 1
501
-
502
- return {
503
- "vertices": vertices,
504
- "solid_face_triangle_vertex_map": solid_face_triangle,
505
- "solid_colors": solid_colors,
506
- "solid_brep_edge_segments": solid_brep_edge_segments,
507
- "solid_brep_vertices": solid_brep_vertices,
508
- "imprinted_assembly": imprinted_assembly,
509
- "imprinted_solids_with_orginal_ids": imprinted_solids_with_orginal_ids,
510
- }
@@ -1,9 +0,0 @@
1
- _version.py,sha256=H7-sGIKTltvB6i41Ij4ifczW_TE-rd9_0VfDTgdon0w,704
2
- cad_to_dagmc/__init__.py,sha256=oCr1P0QnBsf6AH0RZujX7T7tdrb75NazdF70HtqXSfc,528
3
- cad_to_dagmc/core.py,sha256=i3iNhvKOLt2VfdQ8frSLQ5L8y1QC23JprLuoeqqiyD4,43222
4
- cad_to_dagmc/direct_mesh_plugin.py,sha256=iKPYtWQd35Ipxv6g8fZ-r7GFKd1VlCwrSfaNzrGFtf0,24131
5
- cad_to_dagmc-0.9.8.dist-info/licenses/LICENSE,sha256=B8kznH_777JVNZ3HOKDc4Tj24F7wJ68ledaNYeL9sCw,1070
6
- cad_to_dagmc-0.9.8.dist-info/METADATA,sha256=rpYNMTMwcYgI_JqMRCcVlT2q0e8UnMCJACtoue617jc,8994
7
- cad_to_dagmc-0.9.8.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
8
- cad_to_dagmc-0.9.8.dist-info/top_level.txt,sha256=zTi8C64SEBsE5WOtPovnxhOzt-E6Oc5nC3RW6M_5aEA,22
9
- cad_to_dagmc-0.9.8.dist-info/RECORD,,