3 from __future__
import annotations
6 from pathlib
import Path
7 from typing
import ClassVar, Union
11 from ..
import pinocchio_pywrap_default
as pin
12 from ..deprecation
import DeprecatedWarning
13 from ..utils
import npToTuple
14 from .
import BaseVisualizer
18 import meshcat.geometry
as mg
20 import_meshcat_succeed =
False
22 import_meshcat_succeed =
True
27 import xml.etree.ElementTree
as Et
28 from typing
import Any
31 MsgType = dict[str, Union[str, bytes, bool, float,
"MsgType"]]
36 WITH_HPP_FCL_BINDINGS =
True
38 WITH_HPP_FCL_BINDINGS =
False
40 DEFAULT_COLOR_PROFILES = {
41 "gray": ([0.98, 0.98, 0.98], [0.8, 0.8, 0.8]),
42 "white": ([1.0, 1.0, 1.0], [1.0, 1.0, 1.0]),
44 COLOR_PRESETS = DEFAULT_COLOR_PROFILES.copy()
46 FRAME_AXIS_POSITIONS = (
47 np.array([[0, 0, 0], [1, 0, 0], [0, 0, 0], [0, 1, 0], [0, 0, 0], [0, 0, 1]])
52 np.array([[1, 0, 0], [1, 0.6, 0], [0, 1, 0], [0.6, 1, 0], [0, 0, 1], [0, 0.6, 1]])
59 assert color
is not None
60 color = np.asarray(color)
61 assert color.shape == (3,)
62 return color.clip(0.0, 1.0)
66 """Check whether the geometry object contains a Mesh supported by MeshCat"""
67 if geometry_object.meshPath ==
"":
70 file_extension = Path(geometry_object.meshPath).suffix
71 if file_extension.lower()
in [
".dae",
".obj",
".stl"]:
78 homogeneous_transform: np.ndarray, scale: np.ndarray
80 assert homogeneous_transform.shape == (4, 4)
81 assert scale.size == 3
82 scale = np.array(scale).flatten()
83 S = np.diag(np.concatenate((scale, [1.0])))
84 return homogeneous_transform @ S
87 if import_meshcat_succeed:
90 """A cone of the given height and radius. By Three.js convention, the axis
91 of rotational symmetry is aligned with the y-axis.
98 radialSegments: float = 32,
99 openEnded: bool =
False,
107 def lower(self, object_data: Any) -> MsgType:
110 "type":
"ConeGeometry",
118 def __init__(self, dae_path: str, cache: set[str] |
None =
None) ->
None:
119 """Load Collada files with texture images.
121 https://gist.github.com/danzimmerman/a392f8eadcf1166eb5bd80e3922dbdc5
126 dae_path = Path(dae_path)
134 dae_dir = dae_path.parent
135 with dae_path.open()
as text_file:
139 img_resource_paths: list[Path] = []
140 img_lib_element = Et.parse(dae_path).find(
141 "{http://www.collada.org/2005/11/COLLADASchema}library_images"
144 img_resource_paths = [
146 for e
in img_lib_element.iter()
147 if e.tag.count(
"init_from")
151 self.img_resources: dict[str, str] = {}
152 for img_path
in img_resource_paths:
153 img_key = str(img_path)
155 if cache
is not None:
156 if img_path
in cache:
157 self.img_resources[img_key] =
""
162 img_path_abs: Path = img_path
163 if not img_path.is_absolute():
164 img_path_abs = (dae_dir / img_path_abs).resolve()
165 if not img_path_abs.is_file():
166 raise UserWarning(f
"Texture '{img_path}' not found.")
167 with img_path_abs.open(
"rb")
as img_file:
168 img_data = base64.b64encode(img_file.read())
169 img_uri = f
"data:image/png;base64,{img_data.decode('utf-8')}"
170 self.img_resources[img_key] = img_uri
173 """Pack data into a dictionary of the format that must be passed to
174 `Visualizer.window.send`.
177 "type":
"set_object",
180 "metadata": {
"version": 4.5,
"type":
"Object"},
185 "type":
"_meshfile_object",
188 "resources": self.img_resources,
203 """A plane of the given width and height."""
209 widthSegments: float = 1,
210 heightSegments: float = 1,
218 def lower(self, object_data: Any) -> MsgType:
221 "type":
"PlaneGeometry",
230 WITH_HPP_FCL_BINDINGS
231 and tuple(map(int, hppfcl.__version__.split(
"."))) >= (3, 0, 0)
232 and hppfcl.WITH_OCTOMAP
236 boxes = octree.toBoxes()
240 bs = boxes[0][3] / 2.0
241 num_boxes = len(boxes)
243 box_corners = np.array(
256 all_points = np.empty((8 * num_boxes, 3))
257 all_faces = np.empty((12 * num_boxes, 3), dtype=int)
259 for box_id, box_properties
in enumerate(boxes):
260 box_center = box_properties[:3]
262 corners = box_corners + box_center
263 point_range = range(box_id * 8, (box_id + 1) * 8)
264 all_points[point_range, :] = corners
275 all_faces[face_id] = np.array([C, D, B])
276 all_faces[face_id + 1] = np.array([B, A, C])
277 all_faces[face_id + 2] = np.array([A, B, F])
278 all_faces[face_id + 3] = np.array([F, E, A])
279 all_faces[face_id + 4] = np.array([E, F, H])
280 all_faces[face_id + 5] = np.array([H, G, E])
281 all_faces[face_id + 6] = np.array([G, H, D])
282 all_faces[face_id + 7] = np.array([D, C, G])
284 all_faces[face_id + 8] = np.array([A, E, G])
285 all_faces[face_id + 9] = np.array([G, C, A])
287 all_faces[face_id + 10] = np.array([B, H, F])
288 all_faces[face_id + 11] = np.array([H, B, D])
292 colors = np.empty((all_points.shape[0], 3))
293 colors[:] = np.ones(3)
294 mesh = mg.TriangularMeshGeometry(all_points, all_faces, colors)
300 raise NotImplementedError(
"loadOctree need hppfcl with octomap support")
303 if WITH_HPP_FCL_BINDINGS:
306 if isinstance(mesh, (hppfcl.HeightFieldOBBRSS, hppfcl.HeightFieldAABB)):
307 heights = mesh.getHeights()
308 x_grid = mesh.getXGrid()
309 y_grid = mesh.getYGrid()
310 min_height = mesh.getMinHeight()
312 X, Y = np.meshgrid(x_grid, y_grid)
317 num_cells = (nx) * (ny) * 2 + (nx + ny) * 4 + 2
319 num_vertices = X.size
322 faces = np.empty((num_tris, 3), dtype=int)
323 vertices = np.vstack(
327 X.reshape(num_vertices),
328 Y.reshape(num_vertices),
329 heights.reshape(num_vertices),
335 X.reshape(num_vertices),
336 Y.reshape(num_vertices),
337 np.full(num_vertices, min_height),
345 for y_id
in range(ny):
346 for x_id
in range(nx):
347 p0 = x_id + y_id * (nx + 1)
352 faces[face_id] = np.array([p0, p3, p1])
354 faces[face_id] = np.array([p3, p2, p1])
358 p0_low = p0 + num_vertices
359 p1_low = p1 + num_vertices
361 faces[face_id] = np.array([p0, p1_low, p0_low])
363 faces[face_id] = np.array([p0, p1, p1_low])
367 p2_low = p2 + num_vertices
368 p3_low = p3 + num_vertices
370 faces[face_id] = np.array([p3, p3_low, p2_low])
372 faces[face_id] = np.array([p3, p2_low, p2])
376 p0_low = p0 + num_vertices
377 p3_low = p3 + num_vertices
379 faces[face_id] = np.array([p0, p3_low, p3])
381 faces[face_id] = np.array([p0, p0_low, p3_low])
385 p1_low = p1 + num_vertices
386 p2_low = p2 + num_vertices
388 faces[face_id] = np.array([p1, p2_low, p2])
390 faces[face_id] = np.array([p1, p1_low, p2_low])
396 p2 = 2 * num_vertices - 1
399 faces[face_id] = np.array([p0, p1, p2])
401 faces[face_id] = np.array([p0, p2, p3])
404 elif isinstance(mesh, (hppfcl.Convex, hppfcl.BVHModelBase)):
405 if isinstance(mesh, hppfcl.BVHModelBase):
406 num_vertices = mesh.num_vertices
407 num_tris = mesh.num_tris
409 call_triangles = mesh.tri_indices
410 call_vertices = mesh.vertices
412 elif isinstance(mesh, hppfcl.Convex):
413 num_vertices = mesh.num_points
414 num_tris = mesh.num_polygons
416 call_triangles = mesh.polygons
417 call_vertices = mesh.points
419 faces = np.empty((num_tris, 3), dtype=int)
420 for k
in range(num_tris):
421 tri = call_triangles(k)
422 faces[k] = [tri[i]
for i
in range(3)]
424 vertices = call_vertices()
425 vertices = vertices.astype(np.float32)
428 mesh = mg.TriangularMeshGeometry(vertices, faces)
432 vertices.T, color=np.repeat(np.ones((3, 1)), num_vertices, axis=1)
434 mg.PointsMaterial(size=0.002),
442 raise NotImplementedError(
"loadMesh need hppfcl")
446 import meshcat.geometry
as mg
451 [1.0, 0.0, 0.0, 0.0],
452 [0.0, 0.0, -1.0, 0.0],
453 [0.0, 1.0, 0.0, 0.0],
454 [0.0, 0.0, 0.0, 1.0],
457 RotatedCylinder =
type(
458 "RotatedCylinder", (mg.Cylinder,), {
"intrinsic_transform":
lambda self: R}
461 geom = geometry_object.geometry
463 if WITH_HPP_FCL_BINDINGS
and isinstance(geom, hppfcl.ShapeBase):
464 if isinstance(geom, hppfcl.Capsule):
465 if hasattr(mg,
"TriangularMeshGeometry"):
468 obj = RotatedCylinder(2.0 * geom.halfLength, geom.radius)
469 elif isinstance(geom, hppfcl.Cylinder):
470 obj = RotatedCylinder(2.0 * geom.halfLength, geom.radius)
471 elif isinstance(geom, hppfcl.Cone):
472 obj = RotatedCylinder(2.0 * geom.halfLength, 0, geom.radius, 0)
473 elif isinstance(geom, hppfcl.Box):
474 obj = mg.Box(
npToTuple(2.0 * geom.halfSide))
475 elif isinstance(geom, hppfcl.Sphere):
476 obj = mg.Sphere(geom.radius)
477 elif isinstance(geom, hppfcl.ConvexBase):
481 msg = f
"Unsupported geometry type for {geometry_object.name} ({type(geom)})"
482 warnings.warn(msg, category=UserWarning, stacklevel=2)
488 nbv = np.array([
max(radial_resolution, 4),
max(cap_resolution, 4)])
492 vertices = np.zeros((nbv[0] * (2 * nbv[1]) + 2, 3))
493 for j
in range(nbv[0]):
494 phi = (2 * np.pi * j) / nbv[0]
495 for i
in range(nbv[1]):
496 theta = (np.pi / 2 * i) / nbv[1]
497 vertices[position + i, :] = np.array(
499 np.cos(theta) * np.cos(phi) * r,
500 np.cos(theta) * np.sin(phi) * r,
501 -h / 2 - np.sin(theta) * r,
504 vertices[position + i + nbv[1], :] = np.array(
506 np.cos(theta) * np.cos(phi) * r,
507 np.cos(theta) * np.sin(phi) * r,
508 h / 2 + np.sin(theta) * r,
511 position += nbv[1] * 2
512 vertices[-2, :] = np.array([0, 0, -h / 2 - r])
513 vertices[-1, :] = np.array([0, 0, h / 2 + r])
514 indexes = np.zeros((nbv[0] * (4 * (nbv[1] - 1) + 4), 3))
517 last = nbv[0] * (2 * nbv[1]) + 1
518 for j
in range(nbv[0]):
519 j_next = (j + 1) % nbv[0]
520 indexes[index + 0] = np.array(
522 j_next * stride + nbv[1],
527 indexes[index + 1] = np.array(
530 j_next * stride + nbv[1],
534 indexes[index + 2] = np.array(
536 j * stride + nbv[1] - 1,
537 j_next * stride + nbv[1] - 1,
541 indexes[index + 3] = np.array(
543 j_next * stride + 2 * nbv[1] - 1,
544 j * stride + 2 * nbv[1] - 1,
548 for i
in range(nbv[1] - 1):
549 indexes[index + 4 + i * 4 + 0] = np.array(
552 j_next * stride + i + 1,
556 indexes[index + 4 + i * 4 + 1] = np.array(
558 j_next * stride + i + 1,
563 indexes[index + 4 + i * 4 + 2] = np.array(
565 j_next * stride + nbv[1] + i + 1,
566 j_next * stride + nbv[1] + i,
567 j * stride + nbv[1] + i,
570 indexes[index + 4 + i * 4 + 3] = np.array(
572 j_next * stride + nbv[1] + i + 1,
573 j * stride + nbv[1] + i,
574 j * stride + nbv[1] + i + 1,
577 index += 4 * (nbv[1] - 1) + 4
578 return mg.TriangularMeshGeometry(vertices, indexes)
582 """A Pinocchio display using Meshcat"""
585 FRAME_VEL_COLOR = 0x00FF00
586 CAMERA_PRESETS: ClassVar = {
591 "preset1": [np.zeros(3), [1.0, 1.0, 1.0]],
592 "preset2": [[0.0, 0.0, 0.6], [0.8, 1.0, 1.2]],
593 "acrobot": [[0.0, 0.1, 0.0], [0.5, 0.0, 0.2]],
594 "cam_ur": [[0.4, 0.6, -0.2], [1.0, 0.4, 1.2]],
595 "cam_ur2": [[0.4, 0.3, 0.0], [0.5, 0.1, 1.4]],
596 "cam_ur3": [[0.4, 0.3, 0.0], [0.6, 1.3, 0.3]],
597 "cam_ur4": [[-1.0, 0.3, 0.0], [1.3, 0.1, 1.2]],
598 "cam_ur5": [[-1.0, 0.3, 0.0], [-0.05, 1.5, 1.2]],
599 "talos": [[0.0, 1.2, 0.0], [1.5, 0.3, 1.5]],
600 "talos2": [[0.0, 1.1, 0.0], [1.2, 0.6, 1.5]],
606 collision_model=
None,
613 if not import_meshcat_succeed:
615 "Error while importing the viewer client.\n"
616 "Check whether meshcat is properly installed "
617 "(pip install --user meshcat)."
619 raise ImportError(msg)
633 """Return the name of the geometry object inside the viewer."""
634 if geometry_type
is pin.GeometryType.VISUAL:
636 elif geometry_type
is pin.GeometryType.COLLISION:
639 def initViewer(self, viewer=None, open=False, loadModel=False, zmq_url=None):
640 """Start a new MeshCat server and client.
641 Note: the server can also be started separately using the "meshcat-server"
642 command in a terminal:
643 this enables the server to remain active after the current script ends.
646 self.
viewer = meshcat.Visualizer(zmq_url)
if viewer
is None else viewer
673 """Set the background."""
674 if col_top
is not None:
678 assert preset_name
in COLOR_PRESETS.keys()
679 col_top, col_bot = COLOR_PRESETS[preset_name]
684 self.
viewer.set_cam_target(target)
687 self.
viewer.set_cam_pos(position)
690 """Set the camera angle and position using a given preset."""
691 assert preset_key
in self.CAMERA_PRESETS
692 cam_val = self.CAMERA_PRESETS[preset_key]
698 elt.set_property(
"zoom", zoom)
710 import meshcat.geometry
as mg
713 basic_three_js_transform = np.array(
715 [1.0, 0.0, 0.0, 0.0],
716 [0.0, 0.0, -1.0, 0.0],
717 [0.0, 1.0, 0.0, 0.0],
718 [0.0, 0.0, 0.0, 1.0],
721 RotatedCylinder =
type(
724 {
"intrinsic_transform":
lambda self: basic_three_js_transform},
729 geom = geometry_object.geometry
731 if WITH_HPP_FCL_BINDINGS
and isinstance(geom, hppfcl.ShapeBase):
732 if isinstance(geom, hppfcl.Capsule):
733 if hasattr(mg,
"TriangularMeshGeometry"):
736 obj = RotatedCylinder(2.0 * geom.halfLength, geom.radius)
737 elif isinstance(geom, hppfcl.Cylinder):
738 obj = RotatedCylinder(2.0 * geom.halfLength, geom.radius)
739 elif isinstance(geom, hppfcl.Cone):
740 obj = RotatedCylinder(2.0 * geom.halfLength, 0, geom.radius, 0)
741 elif isinstance(geom, hppfcl.Box):
742 obj = mg.Box(
npToTuple(2.0 * geom.halfSide))
743 elif isinstance(geom, hppfcl.Sphere):
744 obj = mg.Sphere(geom.radius)
745 elif isinstance(geom, hppfcl.Plane):
747 To[:3, 3] = geom.d * geom.n
748 TranslatedPlane =
type(
751 {
"intrinsic_transform":
lambda self: To},
753 sx = geometry_object.meshScale[0] * 10
754 sy = geometry_object.meshScale[1] * 10
755 obj = TranslatedPlane(sx, sy)
756 elif isinstance(geom, hppfcl.Ellipsoid):
757 obj = mg.Ellipsoid(geom.radii)
758 elif isinstance(geom, (hppfcl.Plane, hppfcl.Halfspace)):
759 plane_transform: pin.SE3 = pin.SE3.Identity()
761 plane_transform.rotation = pin.Quaternion.FromTwoVectors(
764 TransformedPlane =
type(
767 {
"intrinsic_transform":
lambda self: plane_transform.homogeneous},
769 obj = TransformedPlane(1000, 1000)
770 elif isinstance(geom, hppfcl.ConvexBase):
774 msg = f
"Unsupported geometry type for {geometry_object.name} ({type(geom)})"
775 warnings.warn(msg, category=UserWarning, stacklevel=2)
782 if geometry_object.meshPath ==
"":
784 "Display of geometric primitives is supported only if "
785 "pinocchio is build with HPP-FCL bindings."
787 warnings.warn(msg, category=UserWarning, stacklevel=2)
791 file_extension = Path(geometry_object.meshPath).suffix
792 if file_extension.lower() ==
".dae":
794 elif file_extension.lower() ==
".obj":
795 obj = mg.ObjMeshGeometry.from_file(geometry_object.meshPath)
796 elif file_extension.lower() ==
".stl":
797 obj = mg.StlMeshGeometry.from_file(geometry_object.meshPath)
799 msg = f
"Unknown mesh file format: {geometry_object.meshPath}."
800 warnings.warn(msg, category=UserWarning, stacklevel=2)
806 """Load a single geometry object"""
808 meshcat_node = self.
viewer[node_name]
812 if WITH_HPP_FCL_BINDINGS:
813 if isinstance(geometry_object.geometry, hppfcl.ShapeBase):
816 tuple(map(int, hppfcl.__version__.split(
"."))) >= (3, 0, 0)
817 and hppfcl.WITH_OCTOMAP
818 and isinstance(geometry_object.geometry, hppfcl.OcTree)
824 geometry_object.geometry,
827 hppfcl.HeightFieldOBBRSS,
828 hppfcl.HeightFieldAABB,
831 obj =
loadMesh(geometry_object.geometry)
836 "The geometry object named "
837 + geometry_object.name
838 +
" is not supported by Pinocchio/MeshCat for vizualization."
840 warnings.warn(msg, category=UserWarning, stacklevel=2)
842 except Exception
as e:
844 "Error while loading geometry object: "
845 f
"{geometry_object.name}\nError message:\n{e}"
847 warnings.warn(msg, category=UserWarning, stacklevel=2)
850 if isinstance(obj, mg.Object):
851 meshcat_node.set_object(obj)
852 elif isinstance(obj, (mg.Geometry, mg.ReferenceSceneElement)):
853 material = mg.MeshPhongMaterial()
857 def to_material_color(rgba) -> int:
858 """Convert rgba color as list into rgba color as int"""
860 int(rgba[0] * 255) * 256**2
861 + int(rgba[1] * 255) * 256
866 meshColor = geometry_object.meshColor
870 material.color = to_material_color(meshColor)
872 if float(meshColor[3]) != 1.0:
873 material.transparent =
True
874 material.opacity = float(meshColor[3])
876 geom_material = geometry_object.meshMaterial
877 if geometry_object.overrideMaterial
and isinstance(
880 material.emissive = to_material_color(geom_material.meshEmissionColor)
881 material.specular = to_material_color(geom_material.meshSpecularColor)
882 material.shininess = geom_material.meshShininess * 100.0
884 if isinstance(obj, DaeMeshGeometry):
885 obj.path = meshcat_node.path
886 if geometry_object.overrideMaterial:
887 obj.material = material
888 meshcat_node.window.send(obj)
890 meshcat_node.set_object(obj, material)
894 rootNodeName="pinocchio",
896 collision_color=None,
899 """Load the robot in a MeshCat viewer.
901 rootNodeName: name to give to the robot in the viewer
902 color: deprecated and optional, color to give to both the collision
903 and visual models of the robot. This setting overwrites any color
904 specified in the robot description. Format is a list of four
905 RGBA floating-point numbers (between 0 and 1)
906 collision_color: optional, color to give to the collision model of
907 the robot. Format is a list of four RGBA floating-point numbers
909 visual_color: optional, color to give to the visual model of
910 the robot. Format is a list of four RGBA floating-point numbers
913 if color
is not None:
915 "The 'color' argument is deprecated and will be removed in a "
916 "future version of Pinocchio. Consider using "
917 "'collision_color' and 'visual_color' instead.",
918 category=DeprecatedWarning,
920 collision_color = color
929 if self.collision_model
is not None:
930 for collision
in self.collision_model.geometryObjects:
932 collision, pin.GeometryType.COLLISION, collision_color
938 if self.visual_model
is not None:
939 for visual
in self.visual_model.geometryObjects:
941 visual, pin.GeometryType.VISUAL, visual_color
949 def reload(self, new_geometry_object, geometry_type=None):
950 """Reload a geometry_object given by its name and its type"""
951 if geometry_type == pin.GeometryType.VISUAL:
952 geom_model = self.visual_model
954 geom_model = self.collision_model
955 geometry_type = pin.GeometryType.COLLISION
957 geom_id = geom_model.getGeometryId(new_geometry_object.name)
958 geom_model.geometryObjects[geom_id] = new_geometry_object
960 self.
delete(new_geometry_object, geometry_type)
961 visual = geom_model.geometryObjects[geom_id]
967 def delete(self, geometry_object, geometry_type):
973 Display the robot at configuration q in the viewer by placing all the bodies
988 if geometry_type == pin.GeometryType.VISUAL:
989 geom_model = self.visual_model
990 geom_data = self.visual_data
992 geom_model = self.collision_model
993 geom_data = self.collision_data
996 for visual
in geom_model.geometryObjects:
999 M = geom_data.oMg[geom_model.getGeometryId(visual.name)]
1002 geom = visual.geometry
1003 if WITH_HPP_FCL_BINDINGS
and isinstance(
1004 geom, (hppfcl.Plane, hppfcl.Halfspace)
1007 T.translation += M.rotation @ (geom.d * geom.n)
1014 self.
viewer[visual_name].set_transform(T)
1018 M: pin.SE3 = visual.placement
1021 self.
viewer[visual_name].set_transform(T)
1024 """Add a visual GeometryObject to the viewer, with an optional color."""
1029 if not hasattr(self.
viewer,
"get_image"):
1031 "meshcat.Visualizer does not have the get_image() method."
1032 " You need meshcat >= 0.2.0 to get this feature."
1036 """Capture an image from the Meshcat viewer and return an RGB array."""
1037 if w
is not None or h
is not None:
1039 img = self.
viewer.get_image(w, h)
1041 img = self.
viewer.get_image()
1042 img_arr = np.asarray(img)
1046 """Set whether to display collision objects or not."""
1047 if self.collision_model
is None:
1057 """Set whether to display visual objects or not."""
1058 if self.visual_model
is None:
1067 def displayFrames(self, visibility, frame_ids=None, axis_length=0.2, axis_width=2):
1068 """Set whether to display frames or not."""
1075 """Initializes the frame objects for display."""
1076 import meshcat.geometry
as mg
1081 for fid, frame
in enumerate(self.model.frames):
1082 if frame_ids
is None or fid
in frame_ids:
1083 frame_viz_name = f
"{self.viewerFramesGroupName}/{frame.name}"
1084 self.
viewer[frame_viz_name].set_object(
1087 position=axis_length * FRAME_AXIS_POSITIONS,
1088 color=FRAME_AXIS_COLORS,
1090 mg.LineBasicMaterial(
1091 linewidth=axis_width,
1100 Updates the frame visualizations with the latest transforms from model data.
1104 frame_name = self.model.frames[fid].name
1105 frame_viz_name = f
"{self.viewerFramesGroupName}/{frame_name}"
1106 self.
viewer[frame_viz_name].set_transform(self.data.oMf[fid].homogeneous)
1111 self.model, self.data, frame_id, pin.LOCAL_WORLD_ALIGNED
1113 line_group_name = f
"ee_vel/{frame_id}"
1115 [v_scale * vFr.linear], [frame_id], [line_group_name], [color]
1120 vecs: list[np.ndarray],
1121 frame_ids: list[int],
1122 vec_names: list[str],
1125 """Draw vectors extending from given frames."""
1126 import meshcat.geometry
as mg
1128 if len(vecs) != len(frame_ids)
or len(vecs) != len(vec_names):
1130 "Number of vectors and frames IDs or names is inconsistent."
1132 for i, (fid, v)
in enumerate(zip(frame_ids, vecs)):
1133 frame_pos = self.data.oMf[fid].translation
1134 vertices = np.array([frame_pos, frame_pos + v]).astype(np.float32).T
1136 geometry = mg.PointsGeometry(position=vertices)
1137 geom_object = mg.LineSegments(
1138 geometry, mg.LineBasicMaterial(color=colors[i])
1141 self.
viewer[prefix].set_object(geom_object)
1144 __all__ = [
"MeshcatVisualizer"]