
    ^jIY                        d Z ddlZddlZddlZddlZddlZddlZddlm	Z	 ddl
mZ ddlmZmZ ddlmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZmZmZmZ ddlmZ ddl m!Z! ddl"m#Z# ddl$m%Z% ddlm&Z& ddl'm(Z( ddl)m*Z* ddl+m,Z,m-Z-m.Z. ddl/m0Z0m1Z1 ddl2m3Z3m4Z4 ddl5m6Z6 ddl7m8Z8m9Z9 ddl:m;Z; ddl<m=Z=  G d d      Z>y)a  
build123d exporter/import for 3MF and STL

name: mesher.py
by:   Gumyr
date: Aug 9th 2023

desc:
    This module provides the Mesher class that implements exporting and importing
    both 3MF and STL mesh files.  It uses the 3MF Consortium's Lib3MF library
    (see https://github.com/3MFConsortium/lib3mf).

    Creating a 3MF object involves constructing a valid 3D model conforming to
    the 3MF specification. The resource hierarchy represents the various
    components that make up a 3MF object. The main components required to create
    a 3MF object are:

        Wrapper: The wrapper is the highest-level component representing the
    entire 3MF model. It serves as a container for all other resources and
    provides access to the complete 3D model. The wrapper is the starting point
    for creating and managing the 3MF model.

        Model: The model is a core component that contains the geometric and
    non-geometric resources of the 3D object. It represents the actual 3D
    content, including geometry, materials, colors, textures, and other model
    information.

        Resources: Within the model, various resources are used to define
    different aspects of the 3D object. Some essential resources are:

        a. Mesh: The mesh resource defines the geometry of the 3D object. It
    contains a collection of vertices, triangles, and other geometric
    information that describes the shape.

        b. Components: Components allow you to define complex structures by
    combining multiple meshes together. They are useful for hierarchical
    assemblies and instances.

        c. Materials: Materials define the appearance properties of the
    surfaces, such as color, texture, or surface finish.

        d. Textures: Textures are images applied to the surfaces of the 3D
    object to add detail and realism.

        e. Colors: Colors represent color information used in the 3D model,
    which can be applied to vertices or faces.

        Build Items: Build items are the instances of resources used in the 3D
    model. They specify the usage of resources within the model. For example, a
    build item can refer to a specific mesh, material, and transformation to
    represent an instance of an object.

        Metadata: Metadata provides additional information about the model, such
    as author, creation date, and custom properties.

        Attachments: Attachments can include additional files or data associated
    with the 3MF object, such as texture images or other external resources.

    When creating a 3MF object, you typically start with the wrapper and then
    create or import the necessary resources, such as meshes, materials, and
    textures, to define the 3D content. You then organize the model using build
    items, specifying how the resources are used in the scene. Additionally, you
    can add metadata and attachments as needed to complete the 3MF object.

license:

    Copyright 2023 Gumyr

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
    N)Iterable)BytesIO)PathLikefsdecode)Literal)UUID)Lib3MF)	BRep_Tool)BRepBuilderAPI_MakeFaceBRepBuilderAPI_MakePolygonBRepBuilderAPI_MakeSolidBRepBuilderAPI_Sewing)	BRepGProp)BRepMesh_IncrementalMesh)gp_Pnt)GProp_GProps)TopAbs_ShapeEnum)TopExp_Explorer)TopLoc_Location)TopoDSTopoDS_CompoundTopoDS_Shell)MeshTypeUnit)	TOLERANCEColor)Compound)Shapedowncast)Solid)Shellc                      e Zd ZdZej
                  ej                  j                  ej                  ej                  j                  ej                  ej                  j                  ej                  ej                  j                  ej                  ej                  j                   ej"                  ej                  j$                  iZej)                         D  ci c]  \  }}||
 c}}} Zej.                  ej0                  j2                  ej4                  ej0                  j6                  ej8                  ej0                  j:                  ej<                  ej0                  j>                  iZ e j)                         D  ci c]  \  }}||
 c}}} Z!ej                  fdefdZ"e#defd       Z$e#de%e&   fd       Z'e#de%e&   fd       Z(e#de&fd       Z)e#de*fd	       Z+d
e*de*de*de*de,f
dZ-d Z.de%e/   fdZ0d
e*de*de/fdZ1de%e/   fdZ2e3de4de5de5fd       Z6e3de%e7e5e5e5f      de%e%e&      fd       Z8de4dejr                  fdZ:ddej4                  d d fd!e4e;e4   z  de5de5d"ed#e*d z  d$e<d z  fd%Z=dejr                  de4fd&Z>d'e?e*z  e@z  de%e4   fd(ZAd'e?e*z  e@z  fd)ZBd*eCd+eDd,   fd-ZEy c c}}} w c c}}} w ).MesherzMesher

    Tool for exporting and importing meshed objects stored in 3MF or STL files.

    Args:
        unit (Unit, optional): model units. Defaults to Unit.MM.
    unitc                    || _         t        j                  j                  t        j
                        }t	        j                  t        j                  j                  |d            | _        | j                  j                         | _
        | j                  j                  t        j                  |          g | _        y )Nlib3mf)r$   ospathdirnamer	   __file__WrapperjoinwrapperCreateModelmodelSetUnitr#   _map_b3d_to_3mf_unitmeshes)selfr$   libpaths      I/opt/ringagent/.cad-venv/lib/python3.12/site-packages/build123d/mesher.py__init__zMesher.__init__   sv    	''//&//2~~bggll7H&EF\\--/


666t<=/1    returnc                     | j                   S )zUnit used in the model)r$   )r3   s    r5   
model_unitzMesher.model_unit   s     yyr7   c                 \    | j                   D cg c]  }|j                          c}S c c}w )z1Number of triangles in each of the model's meshes)r2   GetTriangleCountr3   ms     r5   triangle_countszMesher.triangle_counts   s%     /3kk:""$:::   )c                 \    | j                   D cg c]  }|j                          c}S c c}w )z1Number of vertices in each of the models's meshes)r2   GetVertexCountr=   s     r5   vertex_countszMesher.vertex_counts   s%     -1KK8q  "888r@   c                 V    | j                   j                         }|j                         S )zNumber of meshes in the model)r/   GetMeshObjectsCount)r3   mesh_iterators     r5   
mesh_countzMesher.mesh_count   s%     48::3L3L3N""$$r7   c                 R    | j                   j                         \  }}}| d| d| S )z3MF Consortium Lib#MF version.)r-   GetLibraryVersion)r3   majorminormicros       r5   library_versionzMesher.library_version   s4     #ll<<>ue%%))r7   
name_spacenamevaluemetadata_typemust_preservec                     | j                   j                         }|*| j                   j                         }|j                         }|j                  |||||       y)a[  add_meta_data

        Add meta data to the models

        Args:
            name_space (str): categorizer of different metadata entries
            name (str): metadata label
            value (str): metadata content
            metadata_type (str): metadata type
            must_preserve (bool): metadata must not be removed if unused
        N)r/   GetMetaDataGroupAddComponentsObjectAddMetaData)r3   rP   rQ   rR   rS   rT   mdg
componentss           r5   add_meta_datazMesher.add_meta_data   sQ    ( jj))+;26**2P2P2RJ--/C 	
D%Nr7   c                 2   t        j                         j                  j                  j                  }t        |d      5 }|j                         }ddd       | j                  dt        j                  j                  |      dd       y# 1 sw Y   =xY w)zAdd the code calling this method to the 3MF metadata with the custom
        name space `build123d`, name equal to the base file name and the type
        as `python`zutf-8)encodingN	build123dpythonF)rP   rQ   rR   rS   rT   )sys	_getframef_backf_codeco_filenameopenreadr[   r'   r(   basename)r3   caller_file	code_filesource_codes       r5   add_code_to_metadatazMesher.add_code_to_metadata   s     mmo,,33??+0 	+I#..*K	+ 	"!!+." 	 	
	+ 	+s    BBc                 Z   | j                   j                         }g }t        |j                               D ]r  }|j	                  |      }i }|j                         |d<   |j                         |d<   |j                         |d<   |j                         |d<   |j                  |       t |S )zRetrieve all of the metadatarP   rQ   typerR   )
r/   rV   rangeGetMetaDataCountGetMetaDataGetNameSpaceGetNameGetTypeGetValueappend)r3   meta_data_groupmeta_data_contentsi	meta_datameta_data_dicts         r5   get_meta_datazMesher.get_meta_data   s    **557779: 	6A'33A6IN+4+A+A+CN<(%.%6%6%8N6"%.%6%6%8N6"&/&8&8&:N7#%%n5	6 "!r7   c                     | j                   j                         }i }|j                  ||      }|j                         |d<   |j	                         |d<   |S )zIRetrieve the metadata value and type for the provided name space and namerm   rR   )r/   rV   GetMetaDataByKeyrs   rt   )r3   rP   rQ   rv   rw   ry   s         r5   get_meta_data_by_keyzMesher.get_meta_data_by_key   sZ    **557#44ZF	%.%6%6%86"&/&8&8&:7#!!r7   c                 T   g }| j                   D ]  }i }|j                         |d<   |j                         |d<   t        j                  |j                               }t        j                  |   j                  |d<   |j                         \  }}||d<   |j                  |        |S )z+Retrieve the properties from all the meshesrQ   part_numberrm   uuid)r2   rr   GetPartNumberr	   
ObjectTypers   r#   _map_3mf_to_b3d_mesh_typerQ   GetUUIDru   )r3   
propertiesmeshproperty_dicttype_3mf_uuid_valid
uuid_values          r5   get_mesh_propertieszMesher.get_mesh_properties   s    
KK 	-DM$(LLNM&!+/+=+=+?M-(((8H$*$D$DX$N$S$SM&!&*lln#K$.M&!m,	- r7   ocp_meshlinear_deflectionangular_deflectionc           
      
   t               }t        | j                  |d|d       g }g }d}| j                         D ]=  }t	        j
                  |j                  |      }|j                         }	|j                         }
t        d|
dz         D ]b  }|j                  |      j                  |	      }|j                         |j                         |j                         f}|j                  |       d |s|j                  j                         t         j"                  k(  }|rg dng d}|j%                         D ]6  }|j                  |D cg c]  }|j'                  |      |z   dz
   c}       8 ||
z  }@ ||fS c c}w )z*Mesh the shape into vertices and trianglesT)theShapetheLinDeflection
isRelativetheAngDeflectionisInParallelr      )r         )r   r   r   )r   r   wrappedfacesr
   Triangulation_sTransformationNbNodesrn   NodeTransformedXYZru   OrientationtaTopAbs_REVERSED	TrianglesValue)r   r   r   lococp_mesh_vertices	trianglesoffsetfacetpoly_triangulationtrsf
node_countrx   gp_pntpntfacet_reversedordertris                    r5   _mesh_shapezMesher._mesh_shape  su     %%./	
 	^^% 	!E!*!:!:5==#!N%%'D+335J1j1n- .+003??Exxz688:vxxz:!((-. "]]668B<N<NNN!/IYE)335 M  U!K#))A,"7!";!KLMj F%	!& !)++ "Ls   F r   r   c           
      v   t        t        t        j                  t        d      d             }i }d}i }t        |       D ]B  \  }\  }}}	t        ||      t        ||      t        |	|      f}
|
|vr
|||
<   |dz  }||
   ||<   D |D cg c]*  }t        j                  t        j                  dz  |       , }}t        j                  dz  }g }|D ]^  }|d   |d   |d   }}}||   }||   }||   }||k7  s'||k7  s-||k7  s3|j                  t        j                   ||||                   ` ||fS c c}w )N
   r   r   r   r   )introundmathlogr   	enumerater	   Positionctypesc_floatc_uintru   Triangle)r   r   digitsvertex_to_idxnext_idx
vert_tablerx   xyzkeyvvertices_3mfc_uint3triangles_3mfr   abcmapped_amapped_bmapped_cs                         r5   _create_3mf_meshzMesher._create_3mf_mesh6  s{    eDHHY3Q788 
 &&78 	/LAy1aF#U1f%5uQ7GHC-'%-c"A)#.JqM	/ @M
:;FOOV^^a/!45
 

 --!#  	C!fc!fc!f!qA!!}H!!}H!!}H 8#H(<XAU$$OOGHh$IJ	 m,,-
s   	/D6	b3d_shapemesh_3mfc                 6   |j                   r| j                  j                         } | j                  j                  t        |j                          }|j                  t        |j                         |      }|j                  |j                         |       yy)z&Transfer color info from shape to mesh)NameDisplayColorN)
colorr/   AddBaseMaterialGroupr-   FloatRGBAToColortupleAddMaterialstrSetObjectLevelPropertyGetResourceID)r3   r   r   base_material_groupcolor_lib3mfbase_material_ids         r5   
_add_colorzMesher._add_colore  s    ??"&**"A"A"C84<<88%	:PQL2>>)  ?   ++#1135E r7   gMbP?g?Nshape	mesh_typer   r   c                    g }t        |t              r|n|gD ]>  }t        |t              r|j                  t	        |             .|j                  |       @ |D ]   }	| j                  j                         }
t        j                  t        j                  |	      ||      \  }}t        |      dk  s|st        j                  d|	 dd       wt        j                  ||      \  }}|
j!                  ||       |
j#                  t        j$                  |          |	j&                  r|
j)                  |	j&                         |r|
j+                  |       |r|
j-                  t/        |             | j1                  |	|
       |
j3                         st5        d      |
j7                         st        j                  dd       | j8                  j                  |
       | j                  j;                  |
| j<                  j?                                | j                  jA                         }|jC                  |
| j<                  j?                                 y)	a  add_shape

        Add a shape to the 3MF/STL file.

        Args:
            shape (Union[Shape, Iterable[Shape]]): build123d object
            linear_deflection (float, optional): mesh control for edges. Defaults to 0.001.
            angular_deflection (float, optional): mesh control for non-planar surfaces.
                Defaults to 0.1.
            mesh_type (MeshType, optional): 3D printing use of mesh. Defaults to MeshType.MODEL.
            part_number (str, optional): part #. Defaults to None.
            uuid_value (uuid, optional): value from uuid package. Defaults to None.

        Raises:
            RuntimeError: 3mf mesh is invalid
            Warning: Degenerate shape skipped
            Warning: 3mf mesh is not manifold
        r   zDegenerate shape z
 - skippedr   )
stacklevelz3mf mesh is invalidz3mf mesh is not manifoldN)"
isinstancer   r   extendlistru   r/   AddMeshObjectr#   r   copy_moduledeepcopylenwarningswarnr   SetGeometrySetType_map_b3d_mesh_type_3mflabelSetNameSetPartNumberSetUUIDr   r   IsValidRuntimeErrorIsManifoldAndOrientedr2   AddBuildItemr-   GetIdentityTransformrW   AddComponent)r3   r   r   r   r   r   r   shapesinput_shaper   r   r   r   r   r   rZ   s                   r5   	add_shapezMesher.add_shapeq  s   6 $.uh$?5eW 	+K+x0d;/0k*		+   5	SI*.***B*B*DH ,2+=+=$$Y/!",(y $%)'	{*=   +1*A*A!9+'L-
   }= V::9EF  1&&{3  Z1
 OOIx0 ##%"#8991138QG KKx(JJ##Hdll.O.O.QR 779J##Hdll.O.O.QRk5	Sr7   c                    |j                         D cg c]  }t        |j                  dd   }}t               }t	        |j                               D ]  }|j                  |      j                  dd }t	        d      D cg c]
  }|||       }}t        |d   |d   |d   d      }t        |j                               }	|	j                         }
t               }t        j                  |
|       |j                         dk7  s|j!                  |
        |j#                          t%        |j'                               }t)        |t*              rg }t-        |t.        j0                        }|j3                         r{|j5                  t7        t9        j6                  |j;                                            |j=                          |j3                         r\nt)        |t>              sJ t7        |      g}tA        |d       }|D cg c]	  }||us| }}|jB                  s|S tE        |jF                        }|D ]  }|j!                  |jF                          tI        |jI                               }|S c c}w c c}w c c}w )	z'Build build123d object from lib3mf meshr   r   r   r   T)Closec                 \    t        j                  | j                         j                        S )N)r   prodbounding_boxsize)ss    r5   <lambda>z#Mesher._get_shape.<locals>.<lambda>  s    499Q^^=M=R=R3S r7   )r   )%GetVerticesr   Coordinatesr   rn   r<   GetTriangleIndicesr   r   WireFacer   r   SurfaceProperties_sMassAddPerformr   
SewedShaper   r   r   r   TopAbs_SHELLMoreru   r!   r   CurrentNextr   maxis_manifoldr   r   r    )r3   r   pgp_pntsshell_builderrx   tri_indicesocp_verticespolygon_builderface_builderr   facet_propertiesocc_sewed_shape	bd_shellsexplorerouter_shellr	  inner_shellssolid_builderinner_shell	shape_objs                        r5   
_get_shapezMesher._get_shape  sJ    9A8L8L8NO161==1-.OO ./x0023 	)A"..q199!A>K=B1XFGKN3FLF8Qa,q/O 3?3G3G3IJL %%'E+~))%1AB$$&!+!!%(	)" 	"=#;#;#=>o7I&8H8U8UVH--/  v||H4D4D4F'G!HI --/
 o|<<</0I))ST#,Ea0DEE &&01D1DE' 	3Kk112	3---/0	_ P G8 Fs   I=J	JJ	file_namec                    t        |      }t        j                  j                  |      \  }}|dvrt	        d|       | j
                  j                  |dd       }|j                  |       t        j                  | j
                  j                            | _        | j
                  j                         }t        |j                               D ];  }|j                          | j                   j#                  |j%                                = g }| j                   D ]  }| j'                  |      }	|j)                         |	_        |j-                         \  }
}}|rT| j
                  j/                  |
      }|j1                  |      }| j2                  j5                  |      }t7        | |	_        |j#                  |	        |S )a   read

        Args:
            file_name Union[PathLike, str, bytes]: file path

        Raises:
            ValueError: Unknown file format - must be 3mf or stl

        Returns:
            list[Shape]: build123d shapes extracted from mesh file
        z.3mfz.stlUnknown file format r   N)r   r'   r(   splitext
ValueErrorr/   QueryReaderReadFromFiler#   _map_3mf_to_b3d_unitGetUnitr$   rE   rn   rF   MoveNextr2   ru   GetCurrentMeshObjectr,  rr   r   GetObjectLevelPropertyGetBaseMaterialGroupByIDGetDisplayColorr-   ColorToFloatRGBAr   r   )r3   r-  _input_file_extensionreaderrG   _ir   r   r   base_mat_idcolor_indexhas_object_level_propertybase_matbase_mat_colorr   s                   r5   rf   zMesher.read  s    Y'	"$''"2"29"='7734H3IJKK''(<QR(@AI&//

0B0B0DE	 48::3L3L3N++-. 	EB""$KK}AACD	E KK 	!DOOD)E,,.EK ++- @K&? )::>>{K/7/G/G/T#||<<"  $UmMM% 	!  r7   c                     t        |      }t        j                  j                  |      \  }}|dvrt	        d|       | j
                  j                  |dd       }|j                  |       y)zwrite

        Args:
            file_name Union[Pathlike, str, bytes]: file path

        Raises:
            ValueError: Unknown file format - must be 3mf or stl
        r/  r0  r   N)r   r'   r(   r1  r2  r/   QueryWriterWriteToFile)r3   r-  r=  output_file_extensionwriters        r5   writezMesher.write*  sp     Y'	#%77#3#3I#>   (8834I3JKLL''(=ab(AB9%r7   stream	file_type)3mfstlc                     |dvrt        d      | j                  j                  |      }|j                  t	        |j                                      y)zwrite_stream

        Args:
            stream (BytesIO): byte stream
            file_type: output mesh format, either "3mf" or "stl"

        Raises:
            ValueError: Unknown file format - must be 3mf or stl
        >   rN  rO  z(Unknown file format - must be 3mf or stlN)r2  r/   rG  rK  bytesWriteToBuffer)r3   rL  rM  rJ  s       r5   write_streamzMesher.write_stream:  sF     N*GHH''	2U6//123r7   )F__name__
__module____qualname____doc__r   MCr	   	ModelUnit
MicroMeterMM
MilliMeterCM
CentiMeterINInchFTFootMMeterr1   itemsr5  r   OTHERr   OtherMODELModelSUPPORTSupportSOLIDSUPPORTSolidSupportr   r   r6   propertyr:   r   r   r?   rC   rH   r   rO   boolr[   rk   dictr{   r~   r   staticmethodr   floatr   r   r   
MeshObjectr   r   r   r  r,  r   rQ  rf   rK  r   r   rS  ).0kr   s   000r5   r#   r#   z   s    	!!,,!!,,!!,,!!&&!!&&  && .B-G-G-IJJTQAqDJ 	))//))//&++33v00==	 3I2N2N2P Q Q$!QA Q$(GG 2T 2 D   ;c ; ; 9tCy 9 9 %C % %
 * * *
OO O 	O
 O O:
 "tDz ""s "# "$ "T$Z  %,%, %, "%, %,N ,-eUE&9 :;,-S	?,- ,-\
E 
V5F5F 
 $)$'&nn"&"&WSx&WS !WS "	WS
 WS 4ZWS 4KWSr26#4#4 2 2h*hnu4 *e *X&x#~5 & 47 4w|7L 4[ K !Rs   J7J>r#   )?rW  copyr   r   r   r'   r`   r   collections.abcr   ior   r   r   typingr   r   r   
OCP.TopAbsTopAbsr   r&   r	   OCP.BRepr
   OCP.BRepBuilderAPIr   r   r   r   OCP.BRepGPropr   OCP.BRepMeshr   OCP.gpr   	OCP.GPropr   r   
OCP.TopExpr   
OCP.TopLocr   
OCP.TopoDSr   r   r   build123d.build_enumsr   r   build123d.geometryr   r   build123d.topology.compositer   build123d.topology.shape_corer   r   build123d.topology.three_dr    build123d.topology.two_dr!   r#    r7   r5   <module>r     s}   Of    	 
  $  !       $ 1  " ' & & < < 0 / 1 9 , *N4 N4r7   