ray.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import trimesh
  2. import numpy as np
  3. from vedo import show, settings
  4. settings.use_depth_peeling = True
  5. # test on a sphere mesh
  6. mesh = trimesh.creation.icosphere()
  7. # create some rays
  8. ray_origins = np.array([[0, 0, -3], [1, 2, -3]])
  9. ray_directions = np.array([[0, 0, 1], [0, -1, 1]])
  10. # run the mesh-ray query
  11. locations, index_ray, index_tri = mesh.ray.intersects_location(
  12. ray_origins=ray_origins, ray_directions=ray_directions
  13. )
  14. locs = trimesh.points.PointCloud(locations)
  15. # stack rays into line segments for visualization as Path3D
  16. ray_visualize = trimesh.load_path(
  17. np.hstack((ray_origins, ray_origins + ray_directions)).reshape(-1, 2, 3)
  18. )
  19. print("The rays hit the mesh at coordinates:\n", locations)
  20. print(f"The rays with index: {index_ray} hit triangles stored at mesh.faces[{index_tri}]")
  21. # stack rays into line segments for visualization as Path3D
  22. ray_visualize = trimesh.load_path(
  23. np.hstack((ray_origins, ray_origins + ray_directions * 5.0)).reshape(-1, 2, 3)
  24. )
  25. # make mesh white-ish
  26. mesh.visual.face_colors = [200, 200, 250, 100]
  27. mesh.visual.face_colors[index_tri] = [255, 0, 0, 255]
  28. show(mesh, ray_visualize, locs, axes=1).close()