How to use meshcat - 10 common examples

To help you get started, we’ve selected a few meshcat 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 stack-of-tasks / pinocchio / bindings / python / pinocchio / visualize / meshcat_visualizer.py View on Github external
import meshcat.geometry

        viewer_name = self.getViewerNodeName(geometry_object, geometry_type)
        if geometry_object.meshPath == "":
            raise IOError("{} mesh file not found for link {}.".format(str(geometry_type).lower(),geometry_object.name))
        # Get file type from filename extension.
        _, file_extension = os.path.splitext(geometry_object.meshPath)
        if file_extension.lower() == ".dae":
            obj = meshcat.geometry.DaeMeshGeometry.from_file(geometry_object.meshPath)
        elif file_extension.lower() == ".obj":
            obj = meshcat.geometry.ObjMeshGeometry.from_file(geometry_object.meshPath)
        elif file_extension.lower() == ".stl":
            obj = meshcat.geometry.StlMeshGeometry.from_file(geometry_object.meshPath)
        else:
            raise ImportError("Unknown mesh file format: {}.".format(geometry_object.meshPath))
        material = meshcat.geometry.MeshPhongMaterial()
        # Set material color from URDF, converting for triplet of doubles to a single int.
        if color is None:
            meshColor = geometry_object.meshColor
        else:
            meshColor = color
        material.color = int(meshColor[0] * 255) * 256**2 + int(meshColor[1] * 255) * 256 + int(meshColor[2] * 255)
        # Add transparency, if needed.
        if float(meshColor[3]) != 1.0:
            material.transparent = True
            material.opacity = float(meshColor[3])
        self.viewer[viewer_name].set_object(obj, material)
github RobotLocomotion / drake / bindings / pydrake / systems / meshcat_visualizer.py View on Github external
p_PQs = point_cloud_P.xyzs()
        # Use only valid points.
        valid = np.logical_not(np.isnan(p_PQs))
        valid = np.all(valid, axis=0)  # Reduce along XYZ axis.
        p_PQs = p_PQs[:, valid]
        if point_cloud_P.has_rgbs():
            rgbs = point_cloud_P.rgbs()[:, valid]
        else:
            # Need manual broadcasting.
            count = p_PQs.shape[1]
            rgbs = np.tile(np.array([self._default_rgb]).T, (1, count))
        # pydrake `PointCloud.rgbs()` are on [0..255], while meshcat
        # `PointCloud` colors are on [0..1].
        rgbs = rgbs / 255.  # Do not use in-place so we can promote types.
        # Send to meshcat.
        self._meshcat_viz[self._name].set_object(g.PointCloud(p_PQs, rgbs))
        self._meshcat_viz[self._name].set_transform(self._X_WP.matrix())
github stack-of-tasks / pinocchio / bindings / python / pinocchio / visualize / meshcat_visualizer.py View on Github external
def loadViewerGeometryObject(self, geometry_object,geometry_type, color=None):
        """Load a single geometry object"""

        import meshcat.geometry

        viewer_name = self.getViewerNodeName(geometry_object, geometry_type)
        if geometry_object.meshPath == "":
            raise IOError("{} mesh file not found for link {}.".format(str(geometry_type).lower(),geometry_object.name))
        # Get file type from filename extension.
        _, file_extension = os.path.splitext(geometry_object.meshPath)
        if file_extension.lower() == ".dae":
            obj = meshcat.geometry.DaeMeshGeometry.from_file(geometry_object.meshPath)
        elif file_extension.lower() == ".obj":
            obj = meshcat.geometry.ObjMeshGeometry.from_file(geometry_object.meshPath)
        elif file_extension.lower() == ".stl":
            obj = meshcat.geometry.StlMeshGeometry.from_file(geometry_object.meshPath)
        else:
            raise ImportError("Unknown mesh file format: {}.".format(geometry_object.meshPath))
        material = meshcat.geometry.MeshPhongMaterial()
        # Set material color from URDF, converting for triplet of doubles to a single int.
        if color is None:
            meshColor = geometry_object.meshColor
        else:
            meshColor = color
        material.color = int(meshColor[0] * 255) * 256**2 + int(meshColor[1] * 255) * 256 + int(meshColor[2] * 255)
        # Add transparency, if needed.
        if float(meshColor[3]) != 1.0:
            material.transparent = True
            material.opacity = float(meshColor[3])
        self.viewer[viewer_name].set_object(obj, material)
github RobotLocomotion / spartan / modules / spartan / perception / tabletop_segmenter.py View on Github external
normal_sets.append(inlier_normals)
                points_accounted_for[nearby_inds][inlier_inds] = True

        if self.vis is not None:
            n_to_vis = 100
            best_run_k = np.argsort(scores)[-n_to_vis:]
            colors = iter(plt.cm.rainbow(np.linspace(0, 1, n_to_vis)))
            self.vis["perception"]["tabletopsegmenter"]["flippable"].delete()
            for k in best_run_k:
                print("Num %d: Score %f with %d points" %
                      (k, scores[k], point_sets[k].shape[1]))
                color = np.tile(next(colors), [point_sets[k].shape[1], 1]).T
                print("Color shape: ", color.shape)
                self.vis["perception"]["tabletopsegmenter"]["flippable"]\
                    ["%d" % k].set_object(
                        meshcat_g.PointCloud(position=point_sets[k],
                                             color=color,
                                             size=0.001))
github danieljfarrell / pvtrace / pvtrace / scene / renderer.py View on Github external
An optional colour specified as a hex integer. The default colour is
                white.

            Returns
            -------
            identifier : str
                The string identifier used to add the line to the scene.
        """
        vis = self.vis
        line = (start, end)
        self._will_add_expendable_to_scene(line)
        vertices = np.column_stack(line)
        assert vertices.shape[0] == 3  # easy to get this wrong
        identifier = self.get_next_identifer()
        vis[identifier].set_object(
            g.Line(
                g.PointsGeometry(vertices),
                g.MeshBasicMaterial(color=colour, transparency=False, opacity=1),
            )
        )
        self._did_add_expendable_to_scene(identifier)
        return identifier
github stack-of-tasks / pinocchio / bindings / python / pinocchio / visualize / meshcat_visualizer.py View on Github external
def loadViewerGeometryObject(self, geometry_object,geometry_type, color=None):
        """Load a single geometry object"""

        import meshcat.geometry

        viewer_name = self.getViewerNodeName(geometry_object, geometry_type)
        if geometry_object.meshPath == "":
            raise IOError("{} mesh file not found for link {}.".format(str(geometry_type).lower(),geometry_object.name))
        # Get file type from filename extension.
        _, file_extension = os.path.splitext(geometry_object.meshPath)
        if file_extension.lower() == ".dae":
            obj = meshcat.geometry.DaeMeshGeometry.from_file(geometry_object.meshPath)
        elif file_extension.lower() == ".obj":
            obj = meshcat.geometry.ObjMeshGeometry.from_file(geometry_object.meshPath)
        elif file_extension.lower() == ".stl":
            obj = meshcat.geometry.StlMeshGeometry.from_file(geometry_object.meshPath)
        else:
            raise ImportError("Unknown mesh file format: {}.".format(geometry_object.meshPath))
        material = meshcat.geometry.MeshPhongMaterial()
        # Set material color from URDF, converting for triplet of doubles to a single int.
        if color is None:
            meshColor = geometry_object.meshColor
        else:
            meshColor = color
        material.color = int(meshColor[0] * 255) * 256**2 + int(meshColor[1] * 255) * 256 + int(meshColor[2] * 255)
        # Add transparency, if needed.
        if float(meshColor[3]) != 1.0:
            material.transparent = True
            material.opacity = float(meshColor[3])
        self.viewer[viewer_name].set_object(obj, material)
github RobotLocomotion / spartan / modules / spartan / perception / deformable_carrot_fit.py View on Github external
def draw(self, vis):
        vis["perception"]["fit"]["carrot"].set_object(
            meshcat_g.ObjMeshGeometry(
                contents=trimesh.io.wavefront.export_wavefront(self.trimesh)))
        vis["perception"]["fit"]["carrot"].set_transform(self.tf)
github danieljfarrell / pvtrace / pvtrace / scene / renderer.py View on Github external
def add_geometry(self, geometry, pathname, transform):
        vis = self.vis
        material = g.MeshBasicMaterial(
            reflectivity=self.reflectivity, sides=0, wireframe=self.wireframe
        )
        material.transparency = self.transparency
        material.opacity = self.opacity

        if isinstance(geometry, Sphere):
            sphere = geometry
            vis[pathname].set_object(g.Sphere(sphere.radius), material)
            vis[pathname].set_transform(transform)

        elif isinstance(geometry, Cylinder):
            cyl = geometry
            vis[pathname].set_object(g.Cylinder(cyl.length, cyl.radius), material)
            # meshcat cylinder is aligned along y-axis. Align along z then apply the
            # node's transform as normal.
            transform = np.copy(transform)
            # Change basic XYZ -> XZY
            transform[:, [1, 2]] = transform[:, [2, 1]]
            vis[pathname].set_transform(transform)

        elif isinstance(geometry, Mesh):
            obj = meshcat.geometry.StlMeshGeometry.from_stream(
                io.BytesIO(trimesh.exchange.stl.export_stl(geometry.trimesh))
            )
            vis[pathname].set_object(obj, material)
            vis[pathname].set_transform(transform)
        else:
            raise NotImplementedError(
                "Cannot yet add {} to visualiser".format(type(geometry))
github danieljfarrell / pvtrace / pvtrace / scene / renderer.py View on Github external
white.

            Returns
            -------
            identifier : str
                The string identifier used to add the line to the scene.
        """
        vis = self.vis
        line = (start, end)
        self._will_add_expendable_to_scene(line)
        vertices = np.column_stack(line)
        assert vertices.shape[0] == 3  # easy to get this wrong
        identifier = self.get_next_identifer()
        vis[identifier].set_object(
            g.Line(
                g.PointsGeometry(vertices),
                g.MeshBasicMaterial(color=colour, transparency=False, opacity=1),
            )
        )
        self._did_add_expendable_to_scene(identifier)
        return identifier
github RobotLocomotion / spartan / modules / spartan / perception / tabletop_segmenter.py View on Github external
colors = plt.cm.rainbow(curv)
    elif color is not None:
        colors = np.tile(color[0:3], [points.shape[1], 1]).T
    else:
        colors = np.zeros(points.shape) + 1.
    vis["perception"]["tabletopsegmenter"][name].set_object(
        meshcat_g.PointCloud(position=points, color=colors, size=size))
    if with_normals:
        normals = vtkNumpy.getNumpyFromVtk(polyData, "Normals").T
        colors = np.tile([1., 0., 0.], [points.shape[1], 1]).T
        segments = np.zeros((3, normals.shape[1]*2))
        for k in range(normals.shape[1]):
            segments[:, 2*k] = points[:, k]
            segments[:, 2*k+1] = points[:, k] + normals[:, k]*0.05
        vis["perception"]["tabletopsegmenter"][name]["normals"].set_object(
            meshcat_g.LineSegments(position=segments,
                                   color=colors, linewidth=size/2.))