PointCloudRenderer.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /* Author: inmo-jang https://github.com/inmo-jang/unity_assets/tree/master/PointCloudStreaming
  2. * Modifications: Added queue compatibility by Trung-Hoa Ha
  3. */
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using UnityEngine;
  7. using System.IO;
  8. using RosSharp.RosBridgeClient;
  9. // Script can be placed anywhere.
  10. public class PointCloudRenderer : MonoBehaviour
  11. {
  12. public PointCloudSubscriber subscriber { get; set; }
  13. public float pointSize = 1f;
  14. public Transform offset;
  15. // Mesh stores the positions and colours of every point in the cloud.
  16. // The renderer and filter are used to display it.
  17. Mesh mesh;
  18. MeshRenderer meshRenderer;
  19. MeshFilter mf;
  20. [Header("Make sure these lists are minimised or editor will crash")]
  21. private Vector3[] positions = new Vector3[] { new Vector3(0, 0, 0), new Vector3(0, 1, 0) };
  22. private Color[] colours = new Color[] { new Color(1f, 0f, 0f), new Color(0f, 1f, 0f) };
  23. private Vector3[] lastpositions;
  24. private Color[] lastcolours;
  25. void Start()
  26. {
  27. // Give all the required components to the gameObject.
  28. GameObject rosbridge = GameObject.Find("RosBridge");
  29. if(null == rosbridge){
  30. Debug.Log("PointCloudRenderer.cs: RosBridge object not found.");
  31. }
  32. subscriber = rosbridge.GetComponent<PointCloudSubscriber>();
  33. if(subscriber == null){
  34. Debug.Log("PointCloudRenderer.cs: Pointcloud subscriber component not found.");
  35. }
  36. meshRenderer = gameObject.AddComponent<MeshRenderer>();
  37. mf = gameObject.AddComponent<MeshFilter>();
  38. meshRenderer.material = new Material(Shader.Find("Custom/PointCloudShader"));
  39. mesh = new Mesh
  40. {
  41. indexFormat = UnityEngine.Rendering.IndexFormat.UInt32
  42. };
  43. transform.position = offset.position;
  44. transform.rotation = offset.rotation;
  45. }
  46. // Updates mesh object.
  47. void UpdateMesh(){
  48. positions = subscriber.GetPCL();
  49. colours = subscriber.GetPCLColor();
  50. if (positions == null)
  51. {
  52. Debug.Log("PointCloudRenderer.cs: No points to display. Please check the PointcloudSubscriber whether points are received and saved to queue.");
  53. return;
  54. }
  55. mesh.Clear();
  56. mesh.vertices = positions;
  57. mesh.colors = colours;
  58. int[] indices = new int[positions.Length];
  59. for (var i = 0; i < positions.Length; i++)
  60. {
  61. indices[i] = i;
  62. }
  63. mesh.SetIndices(indices, MeshTopology.Points, 0);
  64. mf.mesh = mesh;
  65. }
  66. void Update()
  67. {
  68. transform.position = offset.position;
  69. transform.rotation = offset.rotation;
  70. meshRenderer.material.SetFloat("_PointSize", pointSize);
  71. UpdateMesh();
  72. }
  73. }