import trimesh import json import numpy as np PI = np.pi # 可以是标量(各向同性)或三元组(各向异性) # 例如:1.0 或 [0.08, 0.4, 0.08] MODEL_SCALE = 0.004 GRASP_OFFSET = [0., 0., 0.] # 相对“顶部中心”的偏移 GRASP_ROT = [PI, 0.0, PI] # 欧拉角 (rx, ry, rz), 弧度 def _to_scale_vec(scale): """将标量/数组统一成 3 维缩放向量 [sx, sy, sz].""" arr = np.asarray(scale, dtype=float) if arr.ndim == 0: return [float(arr)] * 3 if arr.shape == (3,): return arr.tolist() raise ValueError(f"MODEL_SCALE 需为标量或长度为3的向量,收到形状: {arr.shape}") def create_model_data(id="vase"): file_path = f"./{id}.glb" save_path = f"./model_data.json" # 1) 读模型并融合为单一 Trimesh with open(file_path, "rb") as f: loaded = trimesh.load(f, file_type="glb") mesh = loaded.to_mesh() if isinstance(loaded, trimesh.Scene) else loaded # 2) 应用缩放(标量或三元向量都可) scale_vec = _to_scale_vec(MODEL_SCALE) mesh.apply_scale(scale_vec) # 支持 float 或 (3,) 向量 # 3) OBB 信息 obb = mesh.bounding_box_oriented center = obb.centroid ext = obb.extents diag = np.linalg.norm(ext) # 4) 计算“底部中心” -> 原点的平移 rotation_matrix = obb.transform[:3, :3] bottom_center = center - rotation_matrix[:, 2] * (ext[2] / 2.0) mesh.apply_translation(-bottom_center) # 5) 更新 OBB obb = mesh.bounding_box_oriented center = obb.centroid ext = obb.extents rotation_matrix = obb.transform[:3, :3] # 6) 顶部中心(现在模型底部已对齐原点,Z 轴正向为“上”) top_center = center + rotation_matrix[:, 2] * (ext[2] / 2.0) # 7) 组合抓取位姿:先平移到顶部中心 -> 旋转 -> 偏移 grasp_translation = trimesh.transformations.translation_matrix(top_center) grasp_rotation = trimesh.transformations.euler_matrix(*GRASP_ROT) grasp_offset = trimesh.transformations.translation_matrix(GRASP_OFFSET) grasp_transform = grasp_translation @ grasp_rotation @ grasp_offset # 8) 可视化 scene = trimesh.Scene(mesh) grasp_sphere = trimesh.creation.icosphere(subdivisions=2, radius=diag * 0.05) grasp_sphere.apply_transform(grasp_transform) grasp_sphere.visual.vertex_colors = np.array([[1.0, 0.0, 0.0, 0.5]] * len(grasp_sphere.vertices)) scene.add_geometry(grasp_sphere) grasp_axis = trimesh.creation.axis(origin_size=0.05, axis_length=diag * 0.2) grasp_axis.apply_transform(grasp_transform) scene.add_geometry(grasp_axis) # 9) 保存 JSON(注意 scale 为三元向量) data = { "center": center.tolist(), "extents": ext.tolist(), "scale": scale_vec, "contact_points_pose": [grasp_transform.tolist()], "transform_matrix": trimesh.transformations.identity_matrix().tolist(), "functional_matrix": [], "orientation_point": grasp_transform.tolist(), "contact_points_group": [], "contact_points_mask": [], "contact_points_discription": [], "target_point_discription": ["Grasp pose at the top edge center."], "functional_point_discription": [""], "orientation_point_discription": ["Grasp pose with adjustable offset and rotation."] } with open(save_path, "w", encoding="utf-8") as f: json.dump(data, f, indent=4, ensure_ascii=False, separators=(",", ": ")) # 10) 显示场景 scene.show() if __name__ == "__main__": create_model_data("vase")