
    Tiw1                         d Z ddlmZ ddl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mZmZ ddlmZmZ  G d de          ZdS )zW
voxel.py
-----------

Convert meshes to a simple voxel data structure and back again.
    )sha256N   )bounds)cachingutil)transformations)log)export_binvox)Geometry   )
morphologyops
transforms)DenseEncodingEncodingc                   v   e Zd ZdZd'dZd Zedefd            Zed             Z	e	j
        d             Z	ed	             Zej
        d
             Zed             Zed             Zed             Zed             Zd Zd Zej        d             Zej        d             Zej        d             Zed             Zej        d             Zd Zd(dZd Zej        d             Zed             Zej        d             Zej        d             Zed             Z d)dZ!d  Z"d! Z#d" Z$d# Z%d'd$Z&d% Z'd& Z(dS )*	VoxelGridz
    Store 3D voxels.
    Nc                 P   |t          j        d          }t          |t           j                  r't	          |                    t                              }|j        t          k    rt          d          t          j
                    | _        || _        t          j        || j                  | _        t          j        | j        j                  | _        i | _        t          |t(                    r| j                            |           d S |t          d|          d S )N   zencoding must have dtype bool)	datastore)id_functionz'metadata should be a dict or None, got )npeye
isinstancendarrayr   astypebooldtype
ValueErrorr   	DataStore_dataencodingr   	Transform
_transformCache__hash___cachemetadatadictupdate)selfr"   	transformr(   s       L/DATA/AppData/hermes/venv/lib/python3.11/site-packages/trimesh/voxel/base.py__init__zVoxelGrid.__init__   s   q		Ih
++ 	<$X__T%:%:;;H>T!!<===&((
 $.yDJOOOm
0CDDDh%% 	UM  *****!SxSSTTT "!    c                 4    | j                                         S )z
        Get the hash of the current transformation matrix.

        Returns
        ------------
        hash : str
          Hash of transformation matrix
        )r!   r&   r+   s    r-   r&   zVoxelGrid.__hash__.   s     z""$$$r/   returnc                     t          t          |                                                                                     S N)r   hashto_bytes	hexdigestr1   s    r-   identifier_hashzVoxelGrid.identifier_hash9   s.    d4jj))++,,66888r/   c                     | j         d         S )z|
        `Encoding` object providing the occupancy grid.

        See `trimesh.voxel.encoding` for implementations.
        r"   )r!   r1   s    r-   r"   zVoxelGrid.encoding=   s     z*%%r/   c                 h   t          |t          j                  rt          |          }n't          |t                    st          d|          t          |j                  dk    rt          d|j                  |j        t          k    rt          d|j                   || j
        d<   d S )Nz"encoding must be an Encoding, got    z#encoding must be rank 3, got shape zencoding must be binary, got r"   )r   r   r   r   r   r   lenshaper   r   r!   )r+   r"   s     r-   r"   zVoxelGrid.encodingF   s    h
++ 	P$X..HHHh// 	PN(NNOOOx~!##U8>UUVVV>T!!MX^MMNNN!)
:r/   c                     | j         j        S )&4x4 homogeneous transformation matrix.r$   matrixr1   s    r-   r,   zVoxelGrid.transformR   s     %%r/   c                     || j         _        dS )r?   Nr@   r+   rA   s     r-   r,   zVoxelGrid.transformW   s     "(r/   c                     | j         j        S )zLocation of voxel at [0, 0, 0].)r$   translationr1   s    r-   rE   zVoxelGrid.translation\   s     **r/   c                     | j         j        S )z
        3-element float representing per-axis scale.

        Raises a `RuntimeError` if `self.transform` has rotation or
        shear components.
        )r$   scaler1   s    r-   rG   zVoxelGrid.scalea   s     $$r/   c                     | j         j        S )a\  
        Uniform scaling factor representing the side length of
        each voxel.

        Returns
        -----------
        pitch : float
          Pitch of the voxels.

        Raises
        ------------
        `RuntimeError`
          If `self.transformation` has rotation or shear
          components of has non-uniform scaling.
        )r$   pitchr1   s    r-   rI   zVoxelGrid.pitchk   s    " $$r/   c                     | j         j        S r4   )r$   unit_volumer1   s    r-   element_volumezVoxelGrid.element_volume~   s    **r/   c                 :    | j                             |           | S r4   )r$   apply_transformrC   s     r-   rN   zVoxelGrid.apply_transform   s    ''///r/   c                     | j         j        \  }}|| _         |                     |dddf                   | j        j        dddf<   | S )z
        Mutate self by stripping leading/trailing planes of zeros.

        Returns
        --------
        self after mutation occurs in-place
        Nr   r;   )r"   strippedindices_to_pointsr$   rA   )r+   r"   paddings      r-   stripzVoxelGrid.strip   sP     !M2' (,(>(>wqqq!t}(M(Mrr1u%r/   c                 d   | j         }t          j        |                    d          dz
  |                    d          dz   g          }| j                            |          }t          j        |                    d          |                    d          g          }d|j	        _
        |S )Nr   axisg      ?F)sparse_indicesbounds_modulecornersminmaxr$   transform_pointsr   arrayflags	writeable)r+   indicesrY   r   s       r-   r   zVoxelGrid.bounds   s    %'[[a[  3&(;(;c(AB
 
 /227;;7;;A;..0C0CDEE!&r/   c                 N    | j         }|d         |d         z
  }d|j        _        |S )Nr   r   F)r   r^   r_   )r+   r   extentss      r-   rb   zVoxelGrid.extents   s*    )fQi'"'r/   c                     | j         j        S r4   )r"   is_emptyr1   s    r-   rd   zVoxelGrid.is_empty   s    }%%r/   c                     | j         j        S )z13-tuple of ints denoting shape of occupancy grid.)r"   r=   r1   s    r-   r=   zVoxelGrid.shape   s     }""r/   c                 >    | j         j                                        S )z+int, number of occupied voxels in the grid.)r"   sumitemr1   s    r-   filled_countzVoxelGrid.filled_count   s     } %%'''r/   c                 ~   t          j        |          }|                     |          }t          j        t          j        |t          j        | j                  k     d          t          j        |dk    d                    }t          j        |          }| j        	                    ||                   ||<   |S )a/  
        Query points to see if the voxel cells they lie in are
        filled or not.

        Parameters
        ----------
        point : (n, 3) float
          Points in space

        Returns
        ---------
        is_filled : (n,) bool
          Is cell occupied or not for each point
        rU   r   )
r   
asanyarraypoints_to_indiceslogical_andallr]   r=   
zeros_liker"   	gather_nd)r+   pointr`   in_range	is_filleds        r-   rt   zVoxelGrid.is_filled   s     e$$((//>F7RXdj111;;;RVGqLWY=Z=Z=Z
 
 M(++	"m55gh6GHH	(r/   holesc                 B    t          j        | j        fd|i|| _        | S )a  
        Mutates self by filling in the encoding according
        to `morphology.fill`.

        Parameters
        ----------
        method : hashable
          Implementation key, one of
          `trimesh.voxel.morphology.fill.fillers` keys
        **kwargs : dict
          Additional kwargs passed through to
          the keyed implementation.

        Returns
        ----------
        self : VoxelGrid
          After replacing encoding with a filled version.
        method)r   fillr"   )r+   rw   kwargss      r-   rx   zVoxelGrid.fill   s)    & #OOfOOOr/   c                 B    t          j        | j                  | _        | S )am  
        Mutates self by removing internal voxels
        leaving only surface elements.

        Surviving elements are those in encoding that are
        adjacent to an empty voxel where adjacency is
        controlled by `structure`.

        Returns
        ----------
        self : VoxelGrid
          After replacing encoding with a surface version.
        )r   surfacer"   r1   s    r-   hollowzVoxelGrid.hollow   s     #*4=99r/   c                 6    t          j        | j                  S )a  
        A marching cubes Trimesh representation of the voxels.

        No effort was made to clean or smooth the result in any way;
        it is merely the result of applying the scikit-image
        measure.marching_cubes function to self.encoding.dense.

        Returns
        ---------
        meshed : trimesh.Trimesh
          Representing the current voxel
          object as returned by marching cubes algorithm.
        )rA   )r   matrix_to_marching_cubesrA   r1   s    r-   marching_cubeszVoxelGrid.marching_cubes   s     +4;????r/   c                     | j         j        S )z
        Return a DENSE matrix of the current voxel encoding.

        Returns
        -------------
        dense : (a, b, c) bool
          Numpy array of dense matrix
          Shortcut to voxel.encoding.dense
        )r"   denser1   s    r-   rA   zVoxelGrid.matrix  s     }""r/   c                      | j         | j        z  S )z
        What is the volume of the filled cells in the current
        voxel object.

        Returns
        ---------
        volume : float
          Volume of filled cells.
        )ri   rL   r1   s    r-   volumezVoxelGrid.volume  s      4#666r/   c                 p    | j                             | j                            t                              S )z
        The center of each filled cell as a list of points.

        Returns
        ----------
        points : (self.filled, 3) float
          Points in space.
        )r$   r\   rW   r   floatr1   s    r-   pointszVoxelGrid.points!  s+     //0C0J0J50Q0QRRRr/   c                     | j         j        S )z6(n, 3) int array of sparse indices of occupied voxels.)r"   rW   r1   s    r-   rW   zVoxelGrid.sparse_indices-  s     }++r/   c                    |t          j        |          }|j        dk    rD| j        }|j        dd         |j        k    r||j                 }n6t          j        d           d}n|j        dvrt          j        d           d}t          j	        | j
                            t                    |          }|                    | j                  }|S )a  
        A rough Trimesh representation of the voxels with a box
        for each filled voxel.

        Parameters
        ----------
        colors : None, (3,) or (4,) float or uint8
          (X, Y, Z, 3) or (X, Y, Z, 4) float or uint8
          Where matrix.shape == (X, Y, Z)

        Returns
        ---------
        mesh : trimesh.Trimesh
          Mesh with one box per filled cell.
        Nr   r;   zcolors incorrect shape!)r;   )r   )centerscolors)r   rl   ndimr"   r=   r   r	   warningr   multiboxrW   r   r   rN   r,   )r+   r   ry   r"   meshs        r-   as_boxeszVoxelGrid.as_boxes2  s    " ]6**F{a=<#x~55 $HN3FFK 9:::!FF\115666|D$7$>$>u$E$EfUUU##DN33r/   c                     | j                             |          }t          j        |                              t
                    S )z
        Convert points to indices in the matrix array.

        Parameters
        ----------
        points: (n, 3) float, point in space

        Returns
        ---------
        indices: (n, 3) int array of indices into self.encoding
        )r$   inverse_transform_pointsr   roundr   int)r+   r   s     r-   rm   zVoxelGrid.points_to_indicesW  s7     99&AAx&&s+++r/   c                 f    | j                             |                    t                              S r4   )r$   r\   r   r   )r+   r`   s     r-   rQ   zVoxelGrid.indices_to_pointsf  s$    //u0E0EFFFr/   c                 j     |                      |                    dd                    j        |i |S )z
        Convert the current set of voxels into a trimesh for visualization
        and show that via its built- in preview method.
        r   N)r   popshow)r+   argsry   s      r-   r   zVoxelGrid.showi  s6    
 >t}}VZZ$7788=tNvNNNr/   c                     t          | j                                        | j        j                                                  S r4   )r   r"   copyr$   rA   r1   s    r-   r   zVoxelGrid.copyp  s1    ++--t/E/J/J/L/LMMMr/   c                    t          |t                    r(|&t          j        |                                          }|dk    rt          d          t          | fi |}t          |d          r|                    |           nRt          |t                    r=t          |d          5 }|                    |           ddd           n# 1 swxY w Y   |S )aH  
        Export the current VoxelGrid.

        Parameters
        ------------
        file_obj : file-like or str
          File or file-name to export to.
        file_type : None or str
          Only 'binvox' currently supported.

        Returns
        ---------
        export : bytes
          Value of export.
        Nbinvoxzonly binvox exports supported!writewb)
r   strr   split_extensionlowerr   r
   hasattrr   open)r+   file_obj	file_typery   exportedfs         r-   exportzVoxelGrid.exports  s     h$$ 	?):,X66<<>>I  =>>> 00008W%% 	"NN8$$$$#&& 	"h%% "!!!" " " " " " " " " " " " " " "s   +CCCc                 f   t          |          }| j                                        }| j        }t	          j        ||                              |dz             }|                     |          }|t          j	        |          z  }|d         }t          |t          j        ||                    S )au  
        Create a new VoxelGrid without rotations, reflections
        or shearing.

        Parameters
        ----------
        shape : (3, int)
          The shape of the returned VoxelGrid.

        Returns
        ----------
        vox : VoxelGrid
          Of the given shape with possibly non-uniform
          scale and translation transformation matrix.
        r   r   )r,   )tupler   r   rb   r   grid_linspacereshapert   r   rl   r   trscale_and_translate)r+   r=   r   rb   r   r   rG   	translates           r-   revoxelizedzVoxelGrid.revoxelized  s      e!!##,#FE22::54<HHv&&"-...1I	"*@	*R*RSSSSr/   c                      t          d          )Nz$TODO : implement voxel concatenation)NotImplementedError)r+   others     r-   __add__zVoxelGrid.__add__  s    !"HIIIr/   )NN)ru   r4   ))__name__
__module____qualname____doc__r.   r&   propertyr   r8   r"   setterr,   rE   rG   rI   rL   rN   rS   r   cache_decoratorr   rb   rd   r=   ri   rt   rx   r|   r   rA   r   r   rW   r   rm   rQ   r   r   r   r   r    r/   r-   r   r      s^        U U U U&	% 	% 	% 9 9 9 9 X9 & & X& _	* 	* _	* & & X& ( ( ( + + X+ % % X% % % X%$ + + X+           & & & # # X# ( ( (  2   ,  " @ @ @  
# 
# X
# 
7 
7 
7 	S 	S 	S , , X,# # # #J, , ,G G GO O ON N N   <T T T2J J J J Jr/   r   )r   hashlibr   numpyr    r   rX   r   r   r   r   	constantsr	   exchange.binvoxr
   parentr   r   r   r   r"   r   r   r   r   r/   r-   <module>r      s              & & & & & &         $ $ $ $ $ $       + + + + + +       ) ) ) ) ) ) ) ) ) ) - - - - - - - -UJ UJ UJ UJ UJ UJ UJ UJ UJ UJr/   