How to use the trimesh.transformations function in trimesh

To help you get started, we’ve selected a few trimesh examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mikedh / trimesh / trimesh / exchange / xml_based.py View on Github external
transform = transforms.pop()
        else:
            # multiple transforms we apply all of them in order
            transform = util.multi_dot(transforms)

        # iterate through the contained mesh geometry elements
        for g in geometry.iter(tag=ns + 'MeshGeometry3D'):
            c_normals = np.array(g.attrib['Normals'].replace(',', ' ').split(),
                                 dtype=np.float64).reshape((-1, 3))

            c_vertices = np.array(
                g.attrib['Positions'].replace(
                    ',', ' ').split(), dtype=np.float64).reshape(
                (-1, 3))
            # bake in the transform as we're saving
            c_vertices = transformations.transform_points(c_vertices,
                                                          transform)

            c_faces = np.array(
                g.attrib['TriangleIndices'].replace(
                    ',', ' ').split(), dtype=np.int64).reshape(
                (-1, 3))

            # save data to a sequence
            vertices.append(c_vertices)
            faces.append(c_faces)
            colors.append(np.tile(diffuse, (len(c_faces), 1)))
            normals.append(c_normals)

    # compile the results into clean numpy arrays
    result = dict()
    result['vertices'], result['faces'] = util.append_faces(vertices,
github mikedh / trimesh / trimesh / bounds.py View on Github external
Theta and phi
        return_data : bool
           Flag for returned

        Returns
        --------
        if return_data:
            transform ((4,4) float)
            radius (float)
            height (float)
        else:
            volume (float)
        """
        to_2D = transformations.spherical_matrix(*spherical,
                                                 axes='rxyz')
        projected = transformations.transform_points(hull,
                                                     matrix=to_2D)
        height = projected[:, 2].ptp()

        try:
            center_2D, radius = nsphere.minimum_nsphere(projected[:, :2])
        except BaseException:
            # in degenerate cases return as infinite volume
            return np.inf

        volume = np.pi * height * (radius ** 2)
        if return_data:
            center_3D = np.append(center_2D, projected[
                                  :, 2].min() + (height * .5))
            transform = np.dot(np.linalg.inv(to_2D),
                               transformations.translation_matrix(center_3D))
            return transform, radius, height
github mikedh / trimesh / trimesh / voxel / transforms.py View on Github external
"""
        Apply the transformation to points (not in-place).

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

        Returns
        ----------
        transformed : (n, 3) float
          Points transformed by matrix
        """
        if self.is_identity:
            return points.copy()
        return tr.transform_points(
            points.reshape(-1, 3), self.matrix).reshape(points.shape)
github mikedh / trimesh / trimesh / bounds.py View on Github external
---------
        spherical : (2,) float
           Theta and phi
        return_data : bool
           Flag for returned

        Returns
        --------
        if return_data:
            transform ((4,4) float)
            radius (float)
            height (float)
        else:
            volume (float)
        """
        to_2D = transformations.spherical_matrix(*spherical,
                                                 axes='rxyz')
        projected = transformations.transform_points(hull,
                                                     matrix=to_2D)
        height = projected[:, 2].ptp()

        try:
            center_2D, radius = nsphere.minimum_nsphere(projected[:, :2])
        except BaseException:
            # in degenerate cases return as infinite volume
            return np.inf

        volume = np.pi * height * (radius ** 2)
        if return_data:
            center_3D = np.append(center_2D, projected[
                                  :, 2].min() + (height * .5))
            transform = np.dot(np.linalg.inv(to_2D),
github mmatl / pyrender / pyrender / node.py View on Github external
def _r_from_q(q):
        q_wxyz = np.roll(q, 1)
        return transformations.quaternion_matrix(q_wxyz)[:3,:3]
github musyoku / gqn-dataset-renderer / pyrender / node.py View on Github external
def _q_from_m(m):
        M = np.eye(4)
        M[:3, :3] = Node._r_from_m(m)
        q_wxyz = transformations.quaternion_from_matrix(M)
        return np.roll(q_wxyz, -1)
github mmatl / pyrender / pyrender / trackball.py View on Github external
motion between this point and the one marked by down().
        """
        point = np.array(point, dtype=np.float32)
        dx, dy = point - self._pdown
        mindim = 0.3 * np.min(self._size)

        target = self._target
        x_axis = self._pose[:3,0].flatten()
        y_axis = self._pose[:3,1].flatten()
        z_axis = self._pose[:3,2].flatten()
        eye = self._pose[:3,3].flatten()

        # Interpret drag as a rotation
        if self._state == Trackball.STATE_ROTATE:
            x_angle = -dx / mindim
            x_rot_mat = transformations.rotation_matrix(
                x_angle, y_axis, target
            )

            y_angle = dy / mindim
            y_rot_mat = transformations.rotation_matrix(
                y_angle, x_axis, target
            )

            self._n_pose = y_rot_mat.dot(x_rot_mat.dot(self._pose))

        # Interpret drag as a roll about the camera axis
        elif self._state == Trackball.STATE_ROLL:
            center = self._size / 2.0
            v_init = self._pdown - center
            v_curr = point - center
            v_init = v_init / np.linalg.norm(v_init)
github mikedh / trimesh / trimesh / creation.py View on Github external
faces_seq = [faces[:, ::-1],
                 faces.copy(),
                 vertical_faces]
    vertices_seq = [vertices_3D,
                    vertices_3D.copy() + [0.0, 0, height],
                    vertical]

    # append sequences into flat nicely indexed arrays
    vertices, faces = util.append_faces(vertices_seq, faces_seq)
    if transform is not None:
        # apply transform here to avoid later bookkeeping
        vertices = tf.transform_points(
            vertices, transform)
        # if the transform flips the winding flip faces back
        # so that the normals will be facing outwards
        if tf.flips_winding(transform):
            # fliplr makes arrays non-contiguous
            faces = np.ascontiguousarray(np.fliplr(faces))
    # create mesh object with passed keywords
    mesh = Trimesh(vertices=vertices,
                   faces=faces,
                   **kwargs)
    # only check in strict mode (unit tests)
    if tol.strict:
        assert mesh.volume > 0.0

    return mesh
github mikedh / trimesh / trimesh / registration.py View on Github external
[-1, 1, 1],
                                   [-1, -1, 1],
                                   [-1, 1, -1],
                                   [1, -1, -1],
                                   [-1, -1, -1]]])

    # loop through permutations and run iterative closest point
    costs = np.ones(len(cubes)) * np.inf
    transforms = [None] * len(cubes)
    centroid = search.centroid

    for i, flip in enumerate(cubes):
        # transform from points to search mesh
        # flipped around the centroid of search
        a_to_b = np.dot(
            transformations.transform_around(flip, centroid),
            np.linalg.inv(search_to_points))

        # run first pass ICP
        matrix, junk, cost = icp(a=points,
                                 b=search,
                                 initial=a_to_b,
                                 max_iterations=int(icp_first),
                                 scale=scale)

        # save transform and costs from ICP
        transforms[i] = matrix
        costs[i] = cost

    # run a final ICP refinement step
    matrix, junk, cost = icp(a=points,
                             b=search,
github mikedh / trimesh / trimesh / voxel / creation.py View on Github external
# Provided edge_factor > 1 and max_iter is large enough, this is
    # sufficient to preserve 6-connectivity at the level of voxels.
    hit = np.round(hit).astype(int)

    # remove duplicates
    unique, inverse = grouping.unique_rows(hit)

    # get the voxel centers in model space
    occupied_index = hit[unique]

    origin_index = occupied_index.min(axis=0)
    origin_position = origin_index * pitch

    return base.VoxelGrid(
        enc.SparseBinaryEncoding(occupied_index - origin_index),
        transform=tr.scale_and_translate(
            scale=pitch, translate=origin_position))