2 from pathlib
import Path
3 from typing
import ClassVar, List
7 from ..
import pinocchio_pywrap_default
as pin
8 from ..deprecation
import DeprecatedWarning
9 from ..utils
import npToTuple
10 from .
import BaseVisualizer
14 import meshcat.geometry
as mg
16 import_meshcat_succeed =
False
18 import_meshcat_succeed =
True
23 import xml.etree.ElementTree
as Et
24 from typing
import Any, Dict, Optional, Set, Union
26 MsgType = Dict[str, Union[str, bytes, bool, float,
"MsgType"]]
31 WITH_HPP_FCL_BINDINGS =
True
33 WITH_HPP_FCL_BINDINGS =
False
35 DEFAULT_COLOR_PROFILES = {
36 "gray": ([0.98, 0.98, 0.98], [0.8, 0.8, 0.8]),
37 "white": ([1.0, 1.0, 1.0], [1.0, 1.0, 1.0]),
39 COLOR_PRESETS = DEFAULT_COLOR_PROFILES.copy()
41 FRAME_AXIS_POSITIONS = (
42 np.array([[0, 0, 0], [1, 0, 0], [0, 0, 0], [0, 1, 0], [0, 0, 0], [0, 0, 1]])
47 np.array([[1, 0, 0], [1, 0.6, 0], [0, 1, 0], [0.6, 1, 0], [0, 0, 1], [0, 0.6, 1]])
54 assert color
is not None
55 color = np.asarray(color)
56 assert color.shape == (3,)
57 return color.clip(0.0, 1.0)
61 """Check whether the geometry object contains a Mesh supported by MeshCat"""
62 if geometry_object.meshPath ==
"":
65 file_extension = Path(geometry_object.meshPath).suffix
66 if file_extension.lower()
in [
".dae",
".obj",
".stl"]:
73 homogeneous_transform: np.ndarray, scale: np.ndarray
75 assert homogeneous_transform.shape == (4, 4)
76 assert scale.size == 3
77 scale = np.array(scale).flatten()
78 S = np.diag(np.concatenate((scale, [1.0])))
79 return homogeneous_transform @ S
82 if import_meshcat_succeed:
85 """A cone of the given height and radius. By Three.js convention, the axis
86 of rotational symmetry is aligned with the y-axis.
93 radialSegments: float = 32,
94 openEnded: bool =
False,
102 def lower(self, object_data: Any) -> MsgType:
105 "type":
"ConeGeometry",
113 def __init__(self, dae_path: str, cache: Optional[Set[str]] =
None) ->
None:
114 """Load Collada files with texture images.
116 https://gist.github.com/danzimmerman/a392f8eadcf1166eb5bd80e3922dbdc5
121 dae_path = Path(dae_path)
129 dae_dir = dae_path.parent
130 with dae_path.open()
as text_file:
134 img_resource_paths: List[Path] = []
135 img_lib_element = Et.parse(dae_path).find(
136 "{http://www.collada.org/2005/11/COLLADASchema}library_images"
139 img_resource_paths = [
141 for e
in img_lib_element.iter()
142 if e.tag.count(
"init_from")
146 self.img_resources: Dict[str, str] = {}
147 for img_path
in img_resource_paths:
148 img_key = str(img_path)
150 if cache
is not None:
151 if img_path
in cache:
152 self.img_resources[img_key] =
""
157 img_path_abs: Path = img_path
158 if not img_path.is_absolute():
159 img_path_abs = (dae_dir / img_path_abs).resolve()
160 if not img_path_abs.is_file():
161 raise UserWarning(f
"Texture '{img_path}' not found.")
162 with img_path_abs.open(
"rb")
as img_file:
163 img_data = base64.b64encode(img_file.read())
164 img_uri = f
"data:image/png;base64,{img_data.decode('utf-8')}"
165 self.img_resources[img_key] = img_uri
168 """Pack data into a dictionary of the format that must be passed to
169 `Visualizer.window.send`.
172 "type":
"set_object",
175 "metadata": {
"version": 4.5,
"type":
"Object"},
180 "type":
"_meshfile_object",
183 "resources": self.img_resources,
198 """A plane of the given width and height."""
204 widthSegments: float = 1,
205 heightSegments: float = 1,
213 def lower(self, object_data: Any) -> MsgType:
216 "type":
"PlaneGeometry",
225 WITH_HPP_FCL_BINDINGS
226 and tuple(map(int, hppfcl.__version__.split(
"."))) >= (3, 0, 0)
227 and hppfcl.WITH_OCTOMAP
231 boxes = octree.toBoxes()
235 bs = boxes[0][3] / 2.0
236 num_boxes = len(boxes)
238 box_corners = np.array(
251 all_points = np.empty((8 * num_boxes, 3))
252 all_faces = np.empty((12 * num_boxes, 3), dtype=int)
254 for box_id, box_properties
in enumerate(boxes):
255 box_center = box_properties[:3]
257 corners = box_corners + box_center
258 point_range = range(box_id * 8, (box_id + 1) * 8)
259 all_points[point_range, :] = corners
270 all_faces[face_id] = np.array([C, D, B])
271 all_faces[face_id + 1] = np.array([B, A, C])
272 all_faces[face_id + 2] = np.array([A, B, F])
273 all_faces[face_id + 3] = np.array([F, E, A])
274 all_faces[face_id + 4] = np.array([E, F, H])
275 all_faces[face_id + 5] = np.array([H, G, E])
276 all_faces[face_id + 6] = np.array([G, H, D])
277 all_faces[face_id + 7] = np.array([D, C, G])
279 all_faces[face_id + 8] = np.array([A, E, G])
280 all_faces[face_id + 9] = np.array([G, C, A])
282 all_faces[face_id + 10] = np.array([B, H, F])
283 all_faces[face_id + 11] = np.array([H, B, D])
287 colors = np.empty((all_points.shape[0], 3))
288 colors[:] = np.ones(3)
289 mesh = mg.TriangularMeshGeometry(all_points, all_faces, colors)
295 raise NotImplementedError(
"loadOctree need hppfcl with octomap support")
298 if WITH_HPP_FCL_BINDINGS:
301 if isinstance(mesh, (hppfcl.HeightFieldOBBRSS, hppfcl.HeightFieldAABB)):
302 heights = mesh.getHeights()
303 x_grid = mesh.getXGrid()
304 y_grid = mesh.getYGrid()
305 min_height = mesh.getMinHeight()
307 X, Y = np.meshgrid(x_grid, y_grid)
312 num_cells = (nx) * (ny) * 2 + (nx + ny) * 4 + 2
314 num_vertices = X.size
317 faces = np.empty((num_tris, 3), dtype=int)
318 vertices = np.vstack(
322 X.reshape(num_vertices),
323 Y.reshape(num_vertices),
324 heights.reshape(num_vertices),
330 X.reshape(num_vertices),
331 Y.reshape(num_vertices),
332 np.full(num_vertices, min_height),
340 for y_id
in range(ny):
341 for x_id
in range(nx):
342 p0 = x_id + y_id * (nx + 1)
347 faces[face_id] = np.array([p0, p3, p1])
349 faces[face_id] = np.array([p3, p2, p1])
353 p0_low = p0 + num_vertices
354 p1_low = p1 + num_vertices
356 faces[face_id] = np.array([p0, p1_low, p0_low])
358 faces[face_id] = np.array([p0, p1, p1_low])
362 p2_low = p2 + num_vertices
363 p3_low = p3 + num_vertices
365 faces[face_id] = np.array([p3, p3_low, p2_low])
367 faces[face_id] = np.array([p3, p2_low, p2])
371 p0_low = p0 + num_vertices
372 p3_low = p3 + num_vertices
374 faces[face_id] = np.array([p0, p3_low, p3])
376 faces[face_id] = np.array([p0, p0_low, p3_low])
380 p1_low = p1 + num_vertices
381 p2_low = p2 + num_vertices
383 faces[face_id] = np.array([p1, p2_low, p2])
385 faces[face_id] = np.array([p1, p1_low, p2_low])
391 p2 = 2 * num_vertices - 1
394 faces[face_id] = np.array([p0, p1, p2])
396 faces[face_id] = np.array([p0, p2, p3])
399 elif isinstance(mesh, (hppfcl.Convex, hppfcl.BVHModelBase)):
400 if isinstance(mesh, hppfcl.BVHModelBase):
401 num_vertices = mesh.num_vertices
402 num_tris = mesh.num_tris
404 call_triangles = mesh.tri_indices
405 call_vertices = mesh.vertices
407 elif isinstance(mesh, hppfcl.Convex):
408 num_vertices = mesh.num_points
409 num_tris = mesh.num_polygons
411 call_triangles = mesh.polygons
412 call_vertices = mesh.points
414 faces = np.empty((num_tris, 3), dtype=int)
415 for k
in range(num_tris):
416 tri = call_triangles(k)
417 faces[k] = [tri[i]
for i
in range(3)]
419 vertices = call_vertices()
420 vertices = vertices.astype(np.float32)
423 mesh = mg.TriangularMeshGeometry(vertices, faces)
427 vertices.T, color=np.repeat(np.ones((3, 1)), num_vertices, axis=1)
429 mg.PointsMaterial(size=0.002),
437 raise NotImplementedError(
"loadMesh need hppfcl")
441 import meshcat.geometry
as mg
446 [1.0, 0.0, 0.0, 0.0],
447 [0.0, 0.0, -1.0, 0.0],
448 [0.0, 1.0, 0.0, 0.0],
449 [0.0, 0.0, 0.0, 1.0],
452 RotatedCylinder =
type(
453 "RotatedCylinder", (mg.Cylinder,), {
"intrinsic_transform":
lambda self: R}
456 geom = geometry_object.geometry
458 if WITH_HPP_FCL_BINDINGS
and isinstance(geom, hppfcl.ShapeBase):
459 if isinstance(geom, hppfcl.Capsule):
460 if hasattr(mg,
"TriangularMeshGeometry"):
463 obj = RotatedCylinder(2.0 * geom.halfLength, geom.radius)
464 elif isinstance(geom, hppfcl.Cylinder):
465 obj = RotatedCylinder(2.0 * geom.halfLength, geom.radius)
466 elif isinstance(geom, hppfcl.Cone):
467 obj = RotatedCylinder(2.0 * geom.halfLength, 0, geom.radius, 0)
468 elif isinstance(geom, hppfcl.Box):
469 obj = mg.Box(
npToTuple(2.0 * geom.halfSide))
470 elif isinstance(geom, hppfcl.Sphere):
471 obj = mg.Sphere(geom.radius)
472 elif isinstance(geom, hppfcl.ConvexBase):
476 msg = f
"Unsupported geometry type for {geometry_object.name} ({type(geom)})"
477 warnings.warn(msg, category=UserWarning, stacklevel=2)
483 nbv = np.array([
max(radial_resolution, 4),
max(cap_resolution, 4)])
487 vertices = np.zeros((nbv[0] * (2 * nbv[1]) + 2, 3))
488 for j
in range(nbv[0]):
489 phi = (2 * np.pi * j) / nbv[0]
490 for i
in range(nbv[1]):
491 theta = (np.pi / 2 * i) / nbv[1]
492 vertices[position + i, :] = np.array(
494 np.cos(theta) * np.cos(phi) * r,
495 np.cos(theta) * np.sin(phi) * r,
496 -h / 2 - np.sin(theta) * r,
499 vertices[position + i + nbv[1], :] = np.array(
501 np.cos(theta) * np.cos(phi) * r,
502 np.cos(theta) * np.sin(phi) * r,
503 h / 2 + np.sin(theta) * r,
506 position += nbv[1] * 2
507 vertices[-2, :] = np.array([0, 0, -h / 2 - r])
508 vertices[-1, :] = np.array([0, 0, h / 2 + r])
509 indexes = np.zeros((nbv[0] * (4 * (nbv[1] - 1) + 4), 3))
512 last = nbv[0] * (2 * nbv[1]) + 1
513 for j
in range(nbv[0]):
514 j_next = (j + 1) % nbv[0]
515 indexes[index + 0] = np.array(
517 j_next * stride + nbv[1],
522 indexes[index + 1] = np.array(
525 j_next * stride + nbv[1],
529 indexes[index + 2] = np.array(
531 j * stride + nbv[1] - 1,
532 j_next * stride + nbv[1] - 1,
536 indexes[index + 3] = np.array(
538 j_next * stride + 2 * nbv[1] - 1,
539 j * stride + 2 * nbv[1] - 1,
543 for i
in range(nbv[1] - 1):
544 indexes[index + 4 + i * 4 + 0] = np.array(
547 j_next * stride + i + 1,
551 indexes[index + 4 + i * 4 + 1] = np.array(
553 j_next * stride + i + 1,
558 indexes[index + 4 + i * 4 + 2] = np.array(
560 j_next * stride + nbv[1] + i + 1,
561 j_next * stride + nbv[1] + i,
562 j * stride + nbv[1] + i,
565 indexes[index + 4 + i * 4 + 3] = np.array(
567 j_next * stride + nbv[1] + i + 1,
568 j * stride + nbv[1] + i,
569 j * stride + nbv[1] + i + 1,
572 index += 4 * (nbv[1] - 1) + 4
573 return mg.TriangularMeshGeometry(vertices, indexes)
577 """A Pinocchio display using Meshcat"""
580 FRAME_VEL_COLOR = 0x00FF00
581 CAMERA_PRESETS: ClassVar = {
586 "preset1": [np.zeros(3), [1.0, 1.0, 1.0]],
587 "preset2": [[0.0, 0.0, 0.6], [0.8, 1.0, 1.2]],
588 "acrobot": [[0.0, 0.1, 0.0], [0.5, 0.0, 0.2]],
589 "cam_ur": [[0.4, 0.6, -0.2], [1.0, 0.4, 1.2]],
590 "cam_ur2": [[0.4, 0.3, 0.0], [0.5, 0.1, 1.4]],
591 "cam_ur3": [[0.4, 0.3, 0.0], [0.6, 1.3, 0.3]],
592 "cam_ur4": [[-1.0, 0.3, 0.0], [1.3, 0.1, 1.2]],
593 "cam_ur5": [[-1.0, 0.3, 0.0], [-0.05, 1.5, 1.2]],
594 "talos": [[0.0, 1.2, 0.0], [1.5, 0.3, 1.5]],
595 "talos2": [[0.0, 1.1, 0.0], [1.2, 0.6, 1.5]],
601 collision_model=
None,
608 if not import_meshcat_succeed:
610 "Error while importing the viewer client.\n"
611 "Check whether meshcat is properly installed "
612 "(pip install --user meshcat)."
614 raise ImportError(msg)
628 """Return the name of the geometry object inside the viewer."""
629 if geometry_type
is pin.GeometryType.VISUAL:
631 elif geometry_type
is pin.GeometryType.COLLISION:
634 def initViewer(self, viewer=None, open=False, loadModel=False, zmq_url=None):
635 """Start a new MeshCat server and client.
636 Note: the server can also be started separately using the "meshcat-server"
637 command in a terminal:
638 this enables the server to remain active after the current script ends.
641 self.
viewer = meshcat.Visualizer(zmq_url)
if viewer
is None else viewer
668 """Set the background."""
669 if col_top
is not None:
673 assert preset_name
in COLOR_PRESETS.keys()
674 col_top, col_bot = COLOR_PRESETS[preset_name]
679 self.
viewer.set_cam_target(target)
682 self.
viewer.set_cam_pos(position)
685 """Set the camera angle and position using a given preset."""
686 assert preset_key
in self.CAMERA_PRESETS
687 cam_val = self.CAMERA_PRESETS[preset_key]
693 elt.set_property(
"zoom", zoom)
705 import meshcat.geometry
as mg
708 basic_three_js_transform = np.array(
710 [1.0, 0.0, 0.0, 0.0],
711 [0.0, 0.0, -1.0, 0.0],
712 [0.0, 1.0, 0.0, 0.0],
713 [0.0, 0.0, 0.0, 1.0],
716 RotatedCylinder =
type(
719 {
"intrinsic_transform":
lambda self: basic_three_js_transform},
724 geom = geometry_object.geometry
726 if WITH_HPP_FCL_BINDINGS
and isinstance(geom, hppfcl.ShapeBase):
727 if isinstance(geom, hppfcl.Capsule):
728 if hasattr(mg,
"TriangularMeshGeometry"):
731 obj = RotatedCylinder(2.0 * geom.halfLength, geom.radius)
732 elif isinstance(geom, hppfcl.Cylinder):
733 obj = RotatedCylinder(2.0 * geom.halfLength, geom.radius)
734 elif isinstance(geom, hppfcl.Cone):
735 obj = RotatedCylinder(2.0 * geom.halfLength, 0, geom.radius, 0)
736 elif isinstance(geom, hppfcl.Box):
737 obj = mg.Box(
npToTuple(2.0 * geom.halfSide))
738 elif isinstance(geom, hppfcl.Sphere):
739 obj = mg.Sphere(geom.radius)
740 elif isinstance(geom, hppfcl.Plane):
742 To[:3, 3] = geom.d * geom.n
743 TranslatedPlane =
type(
746 {
"intrinsic_transform":
lambda self: To},
748 sx = geometry_object.meshScale[0] * 10
749 sy = geometry_object.meshScale[1] * 10
750 obj = TranslatedPlane(sx, sy)
751 elif isinstance(geom, hppfcl.Ellipsoid):
752 obj = mg.Ellipsoid(geom.radii)
753 elif isinstance(geom, (hppfcl.Plane, hppfcl.Halfspace)):
754 plane_transform: pin.SE3 = pin.SE3.Identity()
756 plane_transform.rotation = pin.Quaternion.FromTwoVectors(
759 TransformedPlane =
type(
762 {
"intrinsic_transform":
lambda self: plane_transform.homogeneous},
764 obj = TransformedPlane(1000, 1000)
765 elif isinstance(geom, hppfcl.ConvexBase):
769 msg = f
"Unsupported geometry type for {geometry_object.name} ({type(geom)})"
770 warnings.warn(msg, category=UserWarning, stacklevel=2)
777 if geometry_object.meshPath ==
"":
779 "Display of geometric primitives is supported only if "
780 "pinocchio is build with HPP-FCL bindings."
782 warnings.warn(msg, category=UserWarning, stacklevel=2)
786 file_extension = Path(geometry_object.meshPath).suffix
787 if file_extension.lower() ==
".dae":
789 elif file_extension.lower() ==
".obj":
790 obj = mg.ObjMeshGeometry.from_file(geometry_object.meshPath)
791 elif file_extension.lower() ==
".stl":
792 obj = mg.StlMeshGeometry.from_file(geometry_object.meshPath)
794 msg = f
"Unknown mesh file format: {geometry_object.meshPath}."
795 warnings.warn(msg, category=UserWarning, stacklevel=2)
801 """Load a single geometry object"""
803 meshcat_node = self.
viewer[node_name]
807 if WITH_HPP_FCL_BINDINGS:
808 if isinstance(geometry_object.geometry, hppfcl.ShapeBase):
811 tuple(map(int, hppfcl.__version__.split(
"."))) >= (3, 0, 0)
812 and hppfcl.WITH_OCTOMAP
813 and isinstance(geometry_object.geometry, hppfcl.OcTree)
819 geometry_object.geometry,
822 hppfcl.HeightFieldOBBRSS,
823 hppfcl.HeightFieldAABB,
826 obj =
loadMesh(geometry_object.geometry)
831 "The geometry object named "
832 + geometry_object.name
833 +
" is not supported by Pinocchio/MeshCat for vizualization."
835 warnings.warn(msg, category=UserWarning, stacklevel=2)
837 except Exception
as e:
839 "Error while loading geometry object: "
840 f
"{geometry_object.name}\nError message:\n{e}"
842 warnings.warn(msg, category=UserWarning, stacklevel=2)
845 if isinstance(obj, mg.Object):
846 meshcat_node.set_object(obj)
847 elif isinstance(obj, (mg.Geometry, mg.ReferenceSceneElement)):
848 material = mg.MeshPhongMaterial()
852 def to_material_color(rgba) -> int:
853 """Convert rgba color as list into rgba color as int"""
855 int(rgba[0] * 255) * 256**2
856 + int(rgba[1] * 255) * 256
861 meshColor = geometry_object.meshColor
865 material.color = to_material_color(meshColor)
867 if float(meshColor[3]) != 1.0:
868 material.transparent =
True
869 material.opacity = float(meshColor[3])
871 geom_material = geometry_object.meshMaterial
872 if geometry_object.overrideMaterial
and isinstance(
873 geom_material, pin.GeometryPhongMaterial
875 material.emissive = to_material_color(geom_material.meshEmissionColor)
876 material.specular = to_material_color(geom_material.meshSpecularColor)
877 material.shininess = geom_material.meshShininess * 100.0
879 if isinstance(obj, DaeMeshGeometry):
880 obj.path = meshcat_node.path
881 if geometry_object.overrideMaterial:
882 obj.material = material
883 meshcat_node.window.send(obj)
885 meshcat_node.set_object(obj, material)
889 rootNodeName="pinocchio",
891 collision_color=None,
894 """Load the robot in a MeshCat viewer.
896 rootNodeName: name to give to the robot in the viewer
897 color: deprecated and optional, color to give to both the collision
898 and visual models of the robot. This setting overwrites any color
899 specified in the robot description. Format is a list of four
900 RGBA floating-point numbers (between 0 and 1)
901 collision_color: optional, color to give to the collision model of
902 the robot. Format is a list of four RGBA floating-point numbers
904 visual_color: optional, color to give to the visual model of
905 the robot. Format is a list of four RGBA floating-point numbers
908 if color
is not None:
910 "The 'color' argument is deprecated and will be removed in a "
911 "future version of Pinocchio. Consider using "
912 "'collision_color' and 'visual_color' instead.",
913 category=DeprecatedWarning,
915 collision_color = color
924 if self.collision_model
is not None:
925 for collision
in self.collision_model.geometryObjects:
927 collision, pin.GeometryType.COLLISION, collision_color
933 if self.visual_model
is not None:
934 for visual
in self.visual_model.geometryObjects:
936 visual, pin.GeometryType.VISUAL, visual_color
944 def reload(self, new_geometry_object, geometry_type=None):
945 """Reload a geometry_object given by its name and its type"""
946 if geometry_type == pin.GeometryType.VISUAL:
947 geom_model = self.visual_model
949 geom_model = self.collision_model
950 geometry_type = pin.GeometryType.COLLISION
952 geom_id = geom_model.getGeometryId(new_geometry_object.name)
953 geom_model.geometryObjects[geom_id] = new_geometry_object
955 self.
delete(new_geometry_object, geometry_type)
956 visual = geom_model.geometryObjects[geom_id]
962 def delete(self, geometry_object, geometry_type):
968 Display the robot at configuration q in the viewer by placing all the bodies
971 pin.forwardKinematics(self.model, self.data, q)
983 if geometry_type == pin.GeometryType.VISUAL:
984 geom_model = self.visual_model
985 geom_data = self.visual_data
987 geom_model = self.collision_model
988 geom_data = self.collision_data
990 pin.updateGeometryPlacements(self.model, self.data, geom_model, geom_data)
991 for visual
in geom_model.geometryObjects:
994 M = geom_data.oMg[geom_model.getGeometryId(visual.name)]
997 geom = visual.geometry
998 if WITH_HPP_FCL_BINDINGS
and isinstance(
999 geom, (hppfcl.Plane, hppfcl.Halfspace)
1002 T.translation += M.rotation @ (geom.d * geom.n)
1009 self.
viewer[visual_name].set_transform(T)
1013 M: pin.SE3 = visual.placement
1016 self.
viewer[visual_name].set_transform(T)
1019 """Add a visual GeometryObject to the viewer, with an optional color."""
1024 if not hasattr(self.
viewer,
"get_image"):
1026 "meshcat.Visualizer does not have the get_image() method."
1027 " You need meshcat >= 0.2.0 to get this feature."
1031 """Capture an image from the Meshcat viewer and return an RGB array."""
1032 if w
is not None or h
is not None:
1034 img = self.
viewer.get_image(w, h)
1036 img = self.
viewer.get_image()
1037 img_arr = np.asarray(img)
1041 """Set whether to display collision objects or not."""
1042 if self.collision_model
is None:
1052 """Set whether to display visual objects or not."""
1053 if self.visual_model
is None:
1062 def displayFrames(self, visibility, frame_ids=None, axis_length=0.2, axis_width=2):
1063 """Set whether to display frames or not."""
1070 """Initializes the frame objects for display."""
1071 import meshcat.geometry
as mg
1076 for fid, frame
in enumerate(self.model.frames):
1077 if frame_ids
is None or fid
in frame_ids:
1078 frame_viz_name = f
"{self.viewerFramesGroupName}/{frame.name}"
1079 self.
viewer[frame_viz_name].set_object(
1082 position=axis_length * FRAME_AXIS_POSITIONS,
1083 color=FRAME_AXIS_COLORS,
1085 mg.LineBasicMaterial(
1086 linewidth=axis_width,
1095 Updates the frame visualizations with the latest transforms from model data.
1097 pin.updateFramePlacements(self.model, self.data)
1099 frame_name = self.model.frames[fid].name
1100 frame_viz_name = f
"{self.viewerFramesGroupName}/{frame_name}"
1101 self.
viewer[frame_viz_name].set_transform(self.data.oMf[fid].homogeneous)
1104 pin.updateFramePlacement(self.model, self.data, frame_id)
1105 vFr = pin.getFrameVelocity(
1106 self.model, self.data, frame_id, pin.LOCAL_WORLD_ALIGNED
1108 line_group_name = f
"ee_vel/{frame_id}"
1110 [v_scale * vFr.linear], [frame_id], [line_group_name], [color]
1115 vecs: List[np.ndarray],
1116 frame_ids: List[int],
1117 vec_names: List[str],
1120 """Draw vectors extending from given frames."""
1121 import meshcat.geometry
as mg
1123 if len(vecs) != len(frame_ids)
or len(vecs) != len(vec_names):
1125 "Number of vectors and frames IDs or names is inconsistent."
1127 for i, (fid, v)
in enumerate(zip(frame_ids, vecs)):
1128 frame_pos = self.data.oMf[fid].translation
1129 vertices = np.array([frame_pos, frame_pos + v]).astype(np.float32).T
1131 geometry = mg.PointsGeometry(position=vertices)
1132 geom_object = mg.LineSegments(
1133 geometry, mg.LineBasicMaterial(color=colors[i])
1136 self.
viewer[prefix].set_object(geom_object)
1139 __all__ = [
"MeshcatVisualizer"]