handle_simple.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. from PyQt5.QtCore import QObject, pyqtSlot
  2. import open3d as o3d
  3. import numpy as np
  4. import os
  5. from OCC.Core.TopoDS import TopoDS_Face
  6. class Datahandle(QObject):
  7. def __init__(self):
  8. super().__init__()
  9. self.qml_item = None
  10. self.vertices = np.array([])
  11. self.colors = np.array([])
  12. self.triangles = np.array([]) # 新增:三角面索引
  13. self.normals = np.array([]) # 新增:法线
  14. def load_data(self):
  15. """
  16. 加载 3D 数据(这里用随机点云代替实际文件)
  17. 返回: vertices, colors (numpy arrays)
  18. """
  19. pcd = o3d.geometry.PointCloud()
  20. pcd.points = o3d.utility.Vector3dVector(np.random.rand(5000, 3))
  21. pcd.colors = o3d.utility.Vector3dVector(np.random.rand(5000, 3))
  22. vertices = np.asarray(pcd.points)
  23. colors = np.asarray(pcd.colors)
  24. return vertices, colors
  25. @pyqtSlot('QVariant')
  26. def set3DItem(self, item):
  27. """接收 QML 中的 QML3DItem 实例"""
  28. self.qml_item = item
  29. if self.qml_item:
  30. self.qml_item.set_data(self.vertices, self.colors)
  31. print("✅ 数据已传递给 QML3DItem")
  32. @pyqtSlot(float, float, float)
  33. def onPointPicked(self, x, y, z):
  34. """接收从 QML3DItem 发出的拾取信号"""
  35. print(f"✅ 拾取到点: ({x:.3f}, {y:.3f}, {z:.3f})")
  36. # 这里可以扩展:保存坐标、发送到其他模块等
  37. class Dataload(QObject):
  38. def __init__(self):
  39. super().__init__()
  40. self.qml_item = None
  41. self.vertices = np.array([])
  42. self.colors = np.array([])
  43. self.triangles = np.array([]) # 新增:三角面索引
  44. self.normals = np.array([]) # 新增:法线
  45. self.picking_color_map = {}
  46. def load_data_from_file(self, file_path: str):
  47. """
  48. 使用 numpy-stl 自动识别 STL 格式(兼容旧版本)
  49. """
  50. print(f"📁 正在加载: {file_path}")
  51. if not os.path.exists(file_path):
  52. print(f"❌ 文件不存在: {file_path}")
  53. return np.array([]), np.array([]), np.array([]), np.array([])
  54. ext = os.path.splitext(file_path)[1].lower()
  55. if ext != '.stl':
  56. print(f"❌ 不支持的格式: {ext}")
  57. return np.array([]), np.array([]), np.array([]), np.array([])
  58. try:
  59. from stl import mesh as stl_mesh
  60. # ✅ 自动识别格式(旧版本也支持)
  61. stl_data = stl_mesh.Mesh.from_file(file_path)
  62. # 获取三角面 (N, 3, 3)
  63. vectors = stl_data.vectors.astype(np.float32)
  64. print(f"✅ 加载 {len(vectors)} 个三角面")
  65. # 展平顶点
  66. vertices = vectors.reshape(-1, 3)
  67. print(f"原始顶点数: {len(vertices)}")
  68. # 三角面索引
  69. num_triangles = len(vectors)
  70. triangles = np.arange(num_triangles * 3, dtype=np.int32).reshape(-1, 3)
  71. print(f"三角面数量: {num_triangles}")
  72. # 法线(每个三角面对应一个法线)
  73. normals = stl_data.normals.astype(np.float32)
  74. vertex_normals = np.repeat(normals, 3, axis=0) # 每个顶点复制一次
  75. print(f"法线数量: {len(vertex_normals)}")
  76. # 颜色:使用法线生成
  77. colors = (vertex_normals + 1.0) / 2.0
  78. if np.any(np.isnan(colors)) or np.any(np.isinf(colors)):
  79. colors = np.ones_like(vertex_normals) * 0.8
  80. self.colors = colors
  81. # --- 归一化 ---
  82. if len(vertices) > 0:
  83. min_coords = np.min(vertices, axis=0)
  84. max_coords = np.max(vertices, axis=0)
  85. center = (min_coords + max_coords) / 2.0
  86. scale = np.max(max_coords - min_coords)
  87. if scale > 0:
  88. vertices = (vertices - center) / scale * 2.0
  89. z_range = np.max(vertices[:, 2]) - np.min(vertices[:, 2])
  90. if z_range < 0.1:
  91. z_center = (np.min(vertices[:, 2]) + np.max(vertices[:, 2])) / 2.0
  92. vertices[:, 2] = (vertices[:, 2] - z_center) * (0.2 / z_range) + z_center
  93. self.vertices = vertices
  94. print(f"调整Z轴范围: {z_range:.6f} -> 0.2")
  95. print(f"✅ 加载成功: {file_path}")
  96. self._build_picking_color_map()
  97. return vertices, colors, triangles, vertex_normals
  98. except Exception as e:
  99. print(f"❌ 加载失败: {e}")
  100. return np.array([]), np.array([]), np.array([]), np.array([])
  101. def _build_picking_color_map(self):
  102. self.picking_color_map.clear()
  103. for i in range(len(self.vertices)):
  104. r, g, b = self._get_picking_color(i)
  105. key = (round(r, 5), round(g, 5), round(b, 5))
  106. self.picking_color_map[key] = i
  107. print("✅ picking_color_map 构建完成")
  108. # 调试:打印前几个
  109. print("📊 前5个映射:", list(self.picking_color_map.items())[:5])
  110. def _get_picking_color(self, index):
  111. """根据顶点索引生成唯一颜色 (r,g,b 归一化到 0~1)"""
  112. idx = index + 1 # 避免 0,0,0 黑色
  113. r = (idx) & 0xFF
  114. g = (idx >> 8) & 0xFF
  115. b = (idx >> 16) & 0xFF
  116. return (r / 255.0, g / 255.0, b / 255.0)