
    ^j.?                     ^   d Z ddlZddlZddlZddlZddlmZmZ ddlmZ ddl	m
Z
mZmZ ddl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 ddlmZ ddl m!Z!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/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6 ddl7m8Z8m9Z9m:Z:m;Z;m<Z< ddl=m>Z>m?Z? ddl@mAZAmBZBmCZCmDZDmEZEmFZF ddlGmHZHmIZI ddlJmKZKmLZLmMZMmNZNmOZOmPZP ddlQmRZRmSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[ e/eRe0eSe1eTe3eWe4eXe5eYe6eZiZ\dee]z  e^z  deUfdZ_dee]z  e^z  deRfd Z`eIj                  fdee]z  e^z  d!eIdeTfd"ZaeKfdee]z  e^z  d#ebdece]e]f   fd$Zded%eHj                  d&d'd(d)e]ez  ez  d*efd+eHeceHeHf   z  dz  d,efd-e
d.   e]z  deVeZeTz     fd/       Zge ed0      d%eHj                  d&d'dd1d)e]ez  ez  d*efd+eHeceHeHf   z  dz  d,efd-e
d.   e]z  d2efdz  deVeZeTz     fd3              Zgd%eHj                  d&d'dd1d)e]ez  ez  d*efd+eHeceHeHf   z  dz  d,efd-e
d.   e]z  d2efdz  deVeZeTz     fd4Zgy)5a  
build123d imports

name: importers.py
by:   Gumyr
date: March 1st, 2023

desc:
    This python module contains importers from multiple file formats.

license:

    Copyright 2022 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)PathLikefsdecode)Path)LiteralTextIOoverload)
deprecated)Bnd_Box)BRep_Builder)
BRepBndLib)	BRepTools)gp_Trsf)Quantity_ColorRGBA)RWStl)STEPCAFControl_Reader)TCollection_AsciiStringTCollection_ExtendedString)TDataStd_Name)	TDF_LabelTDF_LabelSequence)TDocStd_Document)TopAbs_FACE)TopExp_Explorer)TopoDS_CompoundTopoDS_EdgeTopoDS_FaceTopoDS_ShapeTopoDS_ShellTopoDS_SolidTopoDS_VertexTopoDS_Wire)XCAFDoc_ColorCurvXCAFDoc_ColorGenXCAFDoc_ColorSurfXCAFDoc_ColorToolXCAFDoc_DocumentTool)ColorAndLabelimport_svg_document)CMFTINMCMMM)AlignUnit)
TOL_DIGITS	TOLERANCEColorLocationVectorto_align_offset)
CompoundEdgeFaceShape	ShapeListShellSolidVertexWiredowncast	file_namereturnc                     t               }t               }t        |       }t        j                  |||       |j                         rt        d|       t        j                  |      S )zImport shape from a BREP file

    Args:
        file_name (Union[PathLike, str, bytes]): brep file

    Raises:
        ValueError: file not found

    Returns:
        Shape: build123d object
    zCould not import )	r   r   r   r   Read_sIsNull
ValueErrorr7   cast)rA   shapebuilderfile_name_strs       L/opt/ringagent/.cad-venv/lib/python3.12/site-packages/build123d/importers.pyimport_breprL   m   sY     NEnGY'MUM73||~,]O<====    filenamec                 N  	
 dt         dt        fd
dt        dt        dz  ffddt        dt        dz  ffddt         dt        dz  fd		dd
t         dz  dt        t
           f	
fdt        j                  j                  |       st        |       i t        d      }t        |      }t        j                  |j                               t        j                  |j                               t!               }|j#                  d       |j%                  d       |j'                  d       |j)                  t+        |              |j-                  |       t/               }        |_        t3        |j0                        dk(  r|j0                  d   }|S )a  import_step

    Extract shapes from a STEP file and return them as a Compound object.

    Args:
        file_name (Union[PathLike, str, bytes]): file path of STEP file to import

    Raises:
        ValueError: can't open file

    Returns:
        Compound: contents of STEP file
    labelrB   c                 *   d}t               }| j                  t        j                         |      r't        |j	                               j                         }dj                  d |D              }|j                  t        j                  dd            S )zExtract name and format c              3   X   K   | ]"  }t        j                  |      d    dk7  s| $ yw)r   CN)unicodedatacategory).0chs     rK   	<genexpr>z0import_step.<locals>.get_name.<locals>.<genexpr>   s(     UB+2F2Fr2J12MQT2TRUs    **z .()____)
r   FindAttributeGetID_sr   Get	ToCStringjoin	translatestr	maketrans)rP   namestd_name
clean_names       rK   get_namezimport_step.<locals>.get_name   sp     ?}446A*8<<>:DDFDWWU$UU
##CMM&&$ABBrM   objNc                 
   t        | j                               }|v r|   S t               }j                  | t        |      xs0 j                  | t
        |      xs j                  | t        |      }|r|nd|<   |   S )z%Get the color of a shape from a cacheN)hashTShaper   GetColorr"   r#   r$   )rg   keycol	has_color_color_cache
color_tools       rK   get_shape_color_from_cachez/import_step.<locals>.get_shape_color_from_cache   s    3::< ,$$ "%6< @""3(8#>@""3(93? 	
 $-C$SC  rM   rH   c                 P    	|       }||S d}d}t        | t              }|j                         rt|j                         } 	|      }|9t	               }t        j                  ||       |j                         }||kD  r|}|}|j                          |j                         rt|S )z9Get the color - take that of the largest Face if multipleNg      )	r   r   MoreCurrentr
   r   Add_sSquareExtentNext)
rH   shape_color
max_extentwinnerexpfacerm   boxextentrq   s
            rK   	get_colorzimport_step.<locals>.get_color   s    07"
e[1hhj;;=D,T2Ci  s+))+J&!'J FHHJ hhj rM   c                     t               }t        j                  | t        |      s6t        j                  | t        |      st        j                  | t
        |      r|S y)z%Get color directly from an XDE label.N)r   r%   
GetColor_sr"   r#   r$   )rP   rm   s     rK   get_label_colorz$import_step.<locals>.get_label_color   sK     "((0A3G ++E3CSI ++E3DcJJrM   parent_tdf_labelc                    t               }| j                  |       nj                  | |       g }t        |j	                               D ]  }|j                  |dz         }j                  |      rt               }j                  ||       n|}t        j                  |            }j                  |      rt               } |      |_        nt        t        |         |      } |      } |      }	 |      }
|xs |	xs |
|_         |      |_        |j%                  t'        j)                  |                   |j+                  |        |S )z+Recursively extract object into an assembly   )r   GetFreeShapesGetComponents_srangeLengthValueIsReference_sr   GetReferredShape_sr@   
GetShape_sIsAssembly_sr7   children
topods_luttypecolorrP   mover4   GetLocation_sappend)r   sub_tdf_labels
sub_shapesisub_tdf_labelref_tdf_labelsub_topo_shape	sub_shapeinstance_colorreferred_colorshape_fallback_colorbuild_assemblyr   r   rf   
shape_tools              rK   r   z#import_step.<locals>.build_assembly   sL   *,#$$^4&&'7H"$
~,,./ 	)A*00Q7M''6 )--m]K -%j&;&;M&JKN&&}5$J	%3M%B	"&tN';<^L	 -];N,];N#,^#< ,VVBVIO&}5IONN8J$<$<]$KLMi(1	)2 rM   XCAFTr   r   N)r   ra   r   r   listr:   ospathexistsFileNotFoundErrorr   r   r&   ShapeTool_sMainColorTool_sr   SetNameModeSetColorModeSetLayerModeReadFiler   Transferr7   r   len)rN   fmtdocreaderrootro   r   rp   r   r   rf   rq   r   s        @@@@@@@@rK   import_stepr      sn   C	 Cc C! !9Kd9R ! *<t*C ,	y 	-?$-F 	"T)9 "T%[ " "H 77>>(#)) :<L
$V
,C
3
C%11#((*=J%11#((*=J"$F
t


OOHX&'
OOC:D"$DM
4==Q}}QKrM   
model_unitc                 >   t        j                  t        |             }|t        j                  k(  rnt        j
                  t
        t        j                  t        t        j                  t        t        j                  t        t        j                  t        t        j                  t        i}	 ||   }t               }|j                  |       t        d|j!                         dz         D ]6  }|j#                  |      }	|	j%                  |       |j'                  ||	       8 t)               }
t+               j-                  |
|       t/        j0                  |
      S # t        $ r6}t        dt        D cg c]  }|j                   nc c}w c}       |d}~ww xY w)a  import_stl

    Extract shape from an STL file and return it as a Face reference object.

    Note that importing with this method and creating a reference is very fast while
    creating an editable model (with Mesher) may take minutes depending on the size
    of the STL file.

    Args:
        file_name (Union[PathLike, str, bytes]): file path of STL file to import
        model_unit (Unit, optional): the default unit used when creating the model. For
            example, Blender defaults to Unit.M. Defaults to Unit.MM.

    Raises:
        ValueError: Could not import file
        ValueError: Invalid model_unit

    Returns:
        Face: STL model
    zmodel_scale must be one of: Nr   )r   
ReadFile_sr   r0   r-   r,   r)   r.   r+   r*   KeyErrorrF   rc   r   SetScaleFactorr   NbNodesNode	TransformSetNoder   r   MakeFacer9   rG   )rA   r   r   conversion_factorscale_factorexcunittransformationr   pr|   s              rK   
import_stlr     sA   , hy12F TWW GGRGGRGGRFFAGGRGGR
	,Z8L
 !%%l3q&..*Q./ 	!AAAKK'NN1a 	!
 =DND&)99T?  	.d/Kd		/K/K.LM	s$   .E 	F&F4FFF	precisionc           	         dt         ffddt        j                  dt         ffd}g dg dg dd}t        |       } t        j                  |       \  }}t
        j                  j                  |       j                  d	      d
   }|j                         r|nd}dd| dg}|D ]  }|D ]  }	t        |	      j                  }
|
dk(  r|j                  d ||	              8||
   dd D cg c]  }|	j                  |    }}dj                  fd|D              }|j                  d||
   d
    d| d         dj                  |      |fS c c}w )a]  translate_to_buildline_code

    Translate the contents of the given svg file into executable build123d/BuildLine code.

    Args:
        file_name (PathLike | str | bytes]): svg file name
        precision (int): # digits to round values to. Defaults to # digits in TOLERANCE

    Returns:
        tuple[str, str]: code, builder instance name
    rB   c                     t        | t              r'd| j                  d dd| j                  d ddS | d dS )N(0.g, ))
isinstancecomplexrealimag)valuer   s    rK   	fmt_valuez/import_svg_as_buildline_code.<locals>.fmt_valueS  sS    eW%uzz"YKq1EJJr)Ao3NaPP9+Q'(rM   curvec                    | j                   }| j                  }| j                  }t        | j                  j
                        }t        | j                  j                        }t        | j                        }t        | j                        }t        | j                        }t        ||z
        t        k  rad|j
                  d	 dd|j                  d	 dd|j
                  d	 dd|j                  d	 dd|d	 dd| j                    dS d|j
                  d	 dd|j                  d	 dd|d	 dd|d	 dd	|d	 dd
|d	 dd|d	 ddS )NzRadiusArc((r   r   r   z), (z), r   zEllipticalCenterArc((z, start_angle=z, arc_size=z, rotation=)centerstartendabsradiusr   r   floatthetadeltarotationr2   	large_arc)
r   r   r   r   x_radiusy_radiusstart_anglearc_sizer   r   s
            rK   arc_to_codez1import_svg_as_buildline_code.<locals>.arc_to_codeX  s   iiu||(()u||(()EKK(%(x("#y0JJr)Ao.bByk?0K LHHR	{!O,Bsxx9+Q.GsByk?+2&'q	*Byk?+2fkk"YKq-I9+Q'r9+Q' (&r)Ao6 7 I;a0 1 I;a03	
rM   )Liner   r   )Bezierr   control1control2r   )r   r   controlr   )r   CubicBezierQuadraticBezier.r   rI   zfrom build123d import *zwith BuildLine() as :Arcz    r   N,c              3   .   K   | ]  } |        y wr    )rW   vr   s     rK   rY   z/import_svg_as_buildline_code.<locals>.<genexpr>  s     !?1)A,!?s   r   r   
)ra   svgpathtoolsr   r   	svg2pathsr   r   basenamesplitisidentifierr   __name__r   __dict__r_   )rA   r   r   
translatorpaths_path_attributesbuilder_namebuildline_coder   r   
class_nameparmvalues
values_strr   s    `            @rK   import_svg_as_buildline_coder  C  s    )C )

<++ 
 
< )I@J
 #I*44Y?E77##I.44S9!<L#/#<#<#><IL!
|nA.N  T 	TEe--JU"%%[-?,@&AB7A*7Mab7QRtennT*RFR!?!??J!!DJ)?)B(C1ZLPQ"RS	TT IIn%|44	 Ss   0ETFid)flip_yalignignore_visibilitylabel_bysvg_filer  r	  r
  r  )r  classzinkscape:labelc                     y r   r   )r  r  r	  r
  r  s        rK   
import_svgr    s     !rM   z~The 'is_inkscape_label' parameter is deprecated and will be removed in build123d 1.0. Use 'label_by="inkscape:label"' instead.)r  r	  r
  r  is_inkscape_labelr  c                     y r   r   )r  r  r	  r
  r  r  s         rK   r  r    s     !rM   c                   |)d}|rd|z   }|d|dz  }t        j                  |d       g }t        j                  dd|      }t	        | ||t        j                  |      	      }t        |j                  j                  |j                  j                        }	t        |j                  j                  |j                  j                        }
t        |	|	|
z   |      }|D ]  \  }}t        |t              rt!        |      }n=t        |t"              rt%        |      }n!t'        d
t)        |      j*                         |j,                  dk7  s|j.                  dk7  r|j1                  |      }|j2                  r&t5        |j7                  |j2                         |_        |j:                  |_        |j=                  |        t?        |      S )a  import_svg

    Args:
        svg_file (Union[str, Path, TextIO]): svg file
        flip_y (bool, optional): flip objects to compensate for svg orientation. Defaults to True.
        align (Align | tuple[Align, Align] | None, optional): alignment of the SVG's viewbox,
            if None, the viewbox's origin will be at `(0,0,0)`. Defaults to Align.MIN.
        ignore_visibility (bool, optional): Defaults to False.
        label_by (str, optional): XML attribute to use for imported shapes' `label` property.
            Defaults to "id".
            Use `inkscape:label` to read labels set from Inkscape's "Layers and Objects" panel.

    Raises:
        ValueError: unexpected shape type

    Returns:
        ShapeList[Union[Wire, Face]]: objects contained in svg
    z+`is_inkscape_label` parameter is deprecatedz	inkscape:z, use `label_by=z	` instead   )
stacklevelz^inkscape:(.+)z/{http://www.inkscape.org/namespaces/inkscape}\1)r  r
  metadatazunexpected shape type: r   ) warningswarnresubr(   r'   Label_byr5   viewboxxywidthheightr6   r   r!   r?   r   r9   rF   r   r   XYr`   wrappedr3   	color_forr   rP   r   r;   )r  r  r	  r
  r  r  msgshapesimporteddoc_xydoc_whoffsetface_or_wirecolor_and_labelrH   s                  rK   r  r    s   6 $;"X-H%h\;;Cca(FvvMxH #+''1	H H$$&&(8(8(:(:;FH$$**H,<,<,C,CDFVVf_e<F)1 %olK0&Ek2&E6tL7I7R7R6STUU88q=FHHMOOF+E==!:!:5==!IJEK%++e  VrM   )h__doc__r   r  rU   r  r   r   pathlibr   typingr   r   r   r   typing_extensionsr	   OCP.Bndr
   OCP.BRepr   OCP.BRepBndLibr   OCP.BRepToolsr   OCP.gpr   OCP.Quantityr   	OCP.RWStlr   OCP.STEPCAFControlr   OCP.TCollectionr   r   OCP.TDataStdr   OCP.TDFr   r   OCP.TDocStdr   
OCP.TopAbsr   
OCP.TopExpr   
OCP.TopoDSr   r   r   r   r   r   r    r!   OCP.XCAFDocr"   r#   r$   r%   r&   ocpsvgr'   r(   build123d.build_commonr)   r*   r+   r,   r-   r.   build123d.build_enumsr/   r0   build123d.geometryr1   r2   r3   r4   r5   r6   build123d.topologyr7   r8   r9   r:   r;   r<   r=   r>   r?   r@   r   ra   bytesrL   r   r   inttupler  MINboolr  r   rM   rK   <module>rJ     sD  > 
 	   !  , ,  (  ! % #  +  4 O & 0 ( " &	 	 	  6 8 8 -    X%%6
 8c>E1  e  0D(S.50 DX DN FJWW 4(S.50 4d 4QU 4r  I5#~%I5I5 38_I5X 
 05		#?C!Dj6!! ! 5&&-	!
 ! 56<! td{! 
! 
@ 05		#?C%)!Dj6!! ! 5&&-	!
 ! 56<! d{! td{!	 

! 05		#?C%)ADj6!A A 5&&-	A
 A 56<A d{A td{ArM   