
    ^jO                        d 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mZ ddl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"m#Z#m$Z$ ddl%m&Z& ddl'm(Z(m)Z) ddl*m+Z+m,Z, ddl-m.Z. ddl/m0Z0m1Z1m2Z2 ddl3m4Z4 ddl5m6Z6 ddl7m8Z8 ddl9m:Z: ddl;m<Z< ddl=m>Z> ddl?m@Z@mAZAmBZB ddlCmDZD ddlEmFZF ddlGmHZHmIZI ddlJmKZK dd lLmMZMmNZNmOZOmPZPmQZQ eIj                  d!fd"ePd#eId$eSd%e:fd&ZTd"ePd'eeUz  eVz  ez  ez  d%eSfd(ZWeIj                  d!d)d*fd"ePd'eeUz  eVz  d#eId+eSd,eXd-eXd%eSfd.ZYeIj                  d/eHj                  fdd0d"ePd'eeUz  eVz  ez  ez  d#eId1eSd2eHd3eUez  dz  d%eSfd4Z[	 	 	 d:d"ePd'eeUz  eVz  d5eXd6eXd7eSd%eSfd8Z\eIj                  d/eHj                  fd"ePd#eId1eSd2eHd%eUf
d9Z]y);a  
build123d 3D Exporters

name: exporters3d.py
by:   Gumyr
date: March 6th, 2024

desc:
    Exporters for 3D models such as STEP.

license:

    Copyright 2024 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)datetime)BytesIO)PathLikefsdecode)Path)BinaryIOcast)PreOrderIter)APIHeaderSection_MakeHeader)BRepMesh_IncrementalMesh)	BRepTools)IFSelect_ReturnStatus)IGESControl_Controller)Interface_Static)MessageMessage_GravityMessage_ProgressRange)RWGltf_CafWriter)STEPCAFControl_ControllerSTEPCAFControl_Writer)STEPControl_ControllerSTEPControl_StepModelType)StlAPI_Writer)TCollection_AsciiStringTCollection_ExtendedStringTCollection_HAsciiString)$TColStd_IndexedDataMapOfStringString)TDataStd_Name)	TDF_Label)TDocStd_Document)TopExp_Explorer)XCAFApp_Application)XCAFDoc_ColorTypeXCAFDoc_DocumentToolXCAFDoc_ShapeTool)XSControl_WorkSession)UNITS_PER_METER)PrecisionModeUnit)Location)CompoundCurvePartShapeSketchF	to_exportunitauto_namingreturnc                    t        t        d            }t        j                         }|j	                  t        d      |       |j                  |       t        j                  |dt        |   z         t        j                  |j                               t        j                  |j                               j                  |       i }dt        dt        fddt        dt        dd	ffd
}t        |       D ]  }|j                   t#        |dd	      }|j%                  |j                   d      }	nO|j'                  |t                     }
 |
      }
|
j)                         roj+                  |
|j                         }	|	j)                         r|	||<   |j,                  s|j.                   |||	        j1                          |S )a  create_xde

    An OpenCASCADE Technology (OCCT) XDE (eXtended Data Exchange) document is a
    sophisticated framework designed for comprehensive CAD data management,
    facilitating not just the geometric modeling of shapes but also the handling
    of associated metadata, such as material properties, color, layering, and
    annotations. This integrated environment supports the organization and
    manipulation of complex assemblies and parts, enabling users to navigate,
    edit, and query both the structure and attributes of CAD models. XDE's
    architecture is particularly beneficial for applications requiring detailed
    interoperability between different CAD systems, offering robust tools for
    data exchange, visualization, and modification while preserving the integrity
    and attributes of the CAD data across various stages of product development.

    Args:
        to_export (Shape): object or assembly
        unit (Unit, optional): shape units. Defaults to Unit.MM.
        auto_naming (bool, optional): whether to use ShapeTool AutoNaming.
            Defaults to False.

    Returns:
        TDocStd_Document: XDE document
    XmlOcafz	MDTV-XCAF   labelr3   c                     | j                         r| S t        j                  |       r2t               }t        j                  | |      r|j                         s|S | S )zReturn a label suitable for assembly operations.

        If `label` is a reference/component label, this resolves and returns
        the referred shape label. Otherwise returns `label` unchanged.
        Null labels are returned as-is.
        )IsNullr%   IsReference_sr   GetReferredShape_s)r7   referreds     N/opt/ringagent/.cad-venv/lib/python3.12/site-packages/build123d/exporters3d.pyresolve_component_parent_labelz3_create_xde.<locals>.resolve_component_parent_label}   sK     <<>L**51 {H!44UHE )    node
node_labelNc                    |j                         ry| j                  rt        j                  |t	        | j                               t        j                  |      rYt               }t        j                  ||      r9|j                         s)t        j                  |t	        | j                               | j                  @t        j                  }	j                  || j                  j                  |       t        j                  |      rWt               }t        j                  ||      r7|j                         s'	j                  || j                  j                  |       t        | t              r| j                   s}t        | t"              r5t%        | j                  t&        j(                        }t        j*                  }nt        | t,              r5t%        | j                  t&        j.                        }t        j*                  }n_t        | t0              r5t%        | j                  t&        j2                        }t        j4                  }nt%               }t        j                  } 
|      }|j7                         r{|j9                         }j;                  ||      }|j                         s'	j                  || j                  j                  |       |j=                          |j7                         rzyyyyy)a  Assign label/color metadata for one XDE node label.

        Behavior:
        - Sets `TDataStd_Name` on the instance label and, when applicable,
          also on the referred shape label so STEP PRODUCT names persist.
        - Sets generic color on the instance label and referred label.
        - For leaf `Compound` wrappers (`Part`, `Sketch`, `Curve`), propagates
          color to relevant sub-shapes (solid/face/edge) using appropriate
          XCAF color channels.
        N)r9   r7   r   Set_sr   r%   r:   r   r;   colorr#   XCAFDoc_ColorGenSetColorwrapped
isinstancer+   childrenr-   r!   taTopAbs_SOLIDXCAFDoc_ColorSurfr/   TopAbs_FACEr,   TopAbs_EDGEXCAFDoc_ColorCurvMoreCurrentAddSubShapeNext)r@   rA   r<   node_color_typeexplorersub_color_typeshape_label_for_subsub_node	sub_label
color_toolr>   
shape_tools            r=   set_name_and_colorz'_create_xde.<locals>.set_name_and_color   s#    ::
,Ftzz,RS ..z:$;%88XN$OO-!'' "<TZZ"H ::!/@@O
DJJ,>,>P ..z:$;%88XN$OO-''$**2D2DoV $)$--dD).t||R__MH%6%H%HNf-.t||R^^LH%6%H%HNe,.t||R^^LH%6%H%HN.0H%6%G%GN&DZ&P#mmo'//1H * 6 67JH UI$++-"++%tzz'9'9> MMO mmo 3@) "r?   parentF)r    r   r"   GetApplication_sNewDocumentInitDocumentr$   SetLengthUnit_sr'   ShapeTool_sMainColorTool_sSetAutoNaming_sr   r.   r
   rG   getattrAddShapegetr9   AddComponentr7   rD   UpdateAssemblies)r0   r1   r2   docapplication	label_mapr\   r@   r]   rA   parent_labelrZ   r>   r[   s              @@@r=   _create_xdero   K   s   6 5i@
AC &668K 6{CSIS!((a/$2G.GH &11#((*=J%11#((*=J
 {+ )+Ii I $=$ =$I =$$ =$B Y' 1<<x.>#,,T\\5AJ$===L9,GL""$#00t||LJ$	$::/tZ0'1* ! Jr?   	file_pathc                     t        |t        t        z  t        z        rt	        |      }nt        t        |      }t        j                  | j                  |      }|dS |S )zExport this shape to a BREP file

    Args:
        to_export (Shape): object or assembly
        file_path: Union[PathLike, str, bytes, BytesIO]: brep file path or memory buffer

    Returns:
        bool: write status
    T)
rH   r   strbytesr   r	   r   r   Write_srG   )r0   rp   return_values      r=   export_breprv      sU     )hnu46Y'	),	$$Y%6%6	BL'49\9r?   MbP?皙?binarylinear_deflectionangular_deflectionc                    | j                   t        d      | j                   }| xj                   t        ddd      z  c_         t        |       D ]!  }|j                  |j                  ||       # t        | |d      }t        t        t        |            |      }	|	j                  d       t               }
t               }t        j                         }|j                         D ]!  }|j!                  t"        j$                         # |	j'                  ||
|      }t)        j*                  | j                         || _         |S )	a  export_gltf

    The glTF (GL Transmission Format) specification primarily focuses on the efficient
    transmission and loading of 3D models as a compact, binary format that is directly
    renderable by graphics APIs like WebGL, OpenGL, and Vulkan. It's designed to store
    detailed 3D model data, including meshes (vertices, normals, textures, etc.),
    animations, materials, and scene hierarchy, among other aspects.

    Args:
        to_export (Shape): object or assembly
        file_path (Union[PathLike, str, bytes]): glTF file path
        unit (Unit, optional): shape units. Defaults to Unit.MM.
        binary (bool, optional): output format. Defaults to False.
        linear_deflection (float, optional): A linear deflection setting which limits
            the distance between a curve and its tessellation. Setting this value too
            low will result in large meshes that can consume computing resources. Setting
            the value too high can result in meshes with a level of detail that is too
            low. The default is a good starting point for a range of cases.
            Defaults to 1e-3.
        angular_deflection (float, optional): Angular deflection setting which limits
            the angle between subsequent segments in a polyline. Defaults to 0.1.

    Raises:
        RuntimeError: Failed to write glTF file

    Returns:
        bool: write status
    z,Shape must have a location to export to glTF)r   r   r   )r6   r   r   iFr2   )theFiletheIsBinaryT)location
ValueErrorr*   r
   rG   meshro   r   r   r   SetParallelr   r   r   DefaultMessenger_sPrintersSetTraceLevelr   Message_FailPerformr   Clean_s)r0   rp   r1   ry   rz   r{   original_locationr@   rk   writer	index_mapprogress	messengerprinterstatuss                  r=   export_gltfr     s3   P !GHH!**(9i== Y' =<<#II');<=
 (	4UKC '(;<&F t46I$&H**,I%%' <o::;< ^^CH5F i''( +I
 Mr?   T)	timestampwrite_pcurvesprecision_moder   c                   t        | |d      }t        j                         }|j                         D ]!  }|j	                  t
        j                         # t               }	t        |	d      }
|
j                  d       |
j                  d       |
j                  d       t        |
j                         j                               }|j                         s8t        d      }|j!                  |
j                         j                                | j"                  r$|j%                  t'        | j"                               |St)        |t*              r)|j-                  t'        |j/                                      n|j-                  t'        |             |j1                  t'        d             t3        j4                          t7        j4                          t9        j4                          t;        j<                  dt?        |             t;        j<                  d|j@                         |
jC                  |tD        jF                         t)        |tH        tJ        tL        f      r|
jO                  tQ        |            }n|
jS                  tU        tV        |            }|tX        jZ                  k(  }|st]        d      |S )	a  export_step

    Export a build123d Shape or assembly with color and label attributes.
    Note that if the color of a node in an assembly isn't set, it will be
    assigned the color of its nearest ancestor.

    Args:
        to_export (Shape): object or assembly
        file_path (Union[PathLike, str, bytes, BytesIO]): step file path
        unit (Unit, optional): shape units. Defaults to Unit.MM.
        write_pcurves (bool, optional): write parametric curves to the STEP file.
            Defaults to True.
        precision_mode (PrecisionMode, optional): geometric data precision.
            Defaults to PrecisionMode.AVERAGE.

    Raises:
        RuntimeError: Unknown Compound type

    Returns:
        bool: success
    Tr}   Fr   	build123dzwrite.surfacecurve.modezwrite.precision.modezFailed to write STEP file)/ro   r   r   r   r   r   r   r&   r   SetColorModeSetLayerModeSetNameModer   WriterModelIsDoneApplyr7   SetNamer   rH   r   SetTimeStamp	isoformatSetOriginatingSystemr   Init_sr   r   r   	SetIVal_sintvalueTransferr   STEPControl_AsIsr   rr   rs   Writer   WriteStreamr	   r   r   IFSelect_RetDoneRuntimeError)r0   rp   r1   r   r   r   rk   r   r   sessionr   headerr   successs                 r=   export_stepr   R  s   @ i4
8C **,I%%' <o::;< $%G"7E2F


t()>)>)@AF==?,Q/V]]_**,-/	@Ai* 89L9L9N OP 8 CD  8 EF $$&!!#!!#8#m:LM5~7K7KL
OOC2CCD)hU34hy12 ##D)$<=->>>G677Nr?   	toleranceangular_toleranceascii_formatc                     t        | j                  |d|d      }|j                          t               }||_        |j                  | j                  t        |            S )a  Export STL

    Exports a shape to a specified STL file.

    Args:
        to_export (Shape): object or assembly
        file_path (Union[PathLike, str, bytes]): The path and file name to write the STL output to.
        tolerance (float, optional): A linear deflection setting which limits the distance
            between a curve and its tessellation. Setting this value too low will result in
            large meshes that can consume computing resources. Setting the value too high can
            result in meshes with a level of detail that is too low. The default is a good
            starting point for a range of cases. Defaults to 1e-3.
        angular_tolerance (float, optional): Angular deflection setting which limits the angle
            between subsequent segments in a polyline. Defaults to 0.1.
        ascii_format (bool, optional): Export the file as ASCII (True) or binary (False)
            STL format. Defaults to False (binary).

    Returns:
        bool: Success
    T)r   rG   r   r   	ASCIIModer   r   )r0   rp   r   r   r   r   r   s          r=   
export_stlr     sV    6 $9d,=tD 	LLN_F#F<<	))8I+>??r?   c                 (   d}d}d}	 t        j                  dd      5 }t        |j                        }ddd       t	        | ||||       t        |d      5 }t        j                  |d	|j                  |d
fid      }	ddd       	j                          	 |	j                         }
|
j                  d      }|
j                  d      dk7  st        |t              st        d|
       	 ||j!                  d       	 t#        j
                  |d      st%        j&                  d|        |S # 1 sw Y   xY w# 1 sw Y   xY w# t        $ r!}t        d|	j                  dd        |d}~ww xY w# ||j!                  d       w w xY w)a  Export a shape to PCBWay for quoting.

    This function writes ``to_export`` to a temporary STEP file, uploads that file
    to PCBWay's external web service, opens the returned pricing page in the
    default browser, and returns the pricing page URL.

    Args:
        to_export (Shape): object or assembly
        unit (Unit, optional): shape units. Defaults to Unit.MM.
        write_pcurves (bool, optional): write parametric curves to the STEP file.
            Defaults to True.
        precision_mode (PrecisionMode, optional): geometric data precision.
            Defaults to PrecisionMode.AVERAGE.

    Returns:
        str: URL of the pricing page
    z-https://www.pcbway.com/common/Build123dUpFile Nz.stepF)suffixdelete)r1   r   r   rbfilezapplication/step)
   x   )filestimeoutz%PCBWay returned a non-JSON response: i  redirectstateSUCCESSz.PCBWay upload failed or returned no redirect: T)
missing_ok   )newz*webbrowser failed to open on pricing page )tempfileNamedTemporaryFiler   namer   openrequestspostraise_for_statusjsonr   r   textrh   rH   rr   unlink
webbrowserwarningswarn)r0   r1   r   r   
upload_urlredirect_url	step_filetmpfresponseresultexcs               r=   export_to_pcbwayr     s   0 AJL I%.((F 	'#SXXI	' 	')	
 )T" 	a}}	3EFG!H	 	!!#	]]_F
 zz*-::g)+:lC3P@I  4Q  -??<Q/B<.QRS	' 	'	 	  	7ds8K7LM	  - !s^   E: D4$E: (EE: E *AE: 4D>9E: E
E: 	E7E22E77E: :F)rw   rx   F)^__doc__r   r   r   r   ior   osr   r   pathlibr   typingr   r	   
OCP.TopAbsTopAbsrJ   r   anytreer
   OCP.APIHeaderSectionr   OCP.BRepMeshr   OCP.BRepToolsr   OCP.IFSelectr   OCP.IGESControlr   OCP.Interfacer   OCP.Messager   r   r   
OCP.RWGltfr   OCP.STEPCAFControlr   r   OCP.STEPControlr   r   
OCP.StlAPIr   OCP.TCollectionr   r   r   OCP.TColStdr   OCP.TDataStdr   OCP.TDFr   OCP.TDocStdr    
OCP.TopExpr!   OCP.XCAFAppr"   OCP.XCAFDocr#   r$   r%   OCP.XSControlr&   build123d.build_commonr'   build123d.build_enumsr(   r)   build123d.geometryr*   build123d.topologyr+   r,   r-   r.   r/   MMboolro   rr   rs   rv   floatr   AVERAGEr   r   r    r?   r=   <module>r     s  >      !  !     < 1 # . 2 * G G ' O M $ 
 = &  ( & + R R / 2 5 ' C C $(77^^ ^9=^^B::#~%/(:: 
:2 $ #MM#~%M M 	M
 M M 
Mf $1$9$9R (,RR#~%/(:R R 	R
 "R X~$R 
Rp "#@#@#~%#@ #@ 	#@
 #@ 
#@P $1$9$9	GG
G G "	G
 	Gr?   