PointCloudData.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // Pcx - Point cloud importer & renderer for Unity
  2. // https://github.com/keijiro/Pcx
  3. using UnityEngine;
  4. using System.Collections.Generic;
  5. namespace TriLibCore.Samples
  6. {
  7. /// A container class optimized for compute buffer.
  8. public sealed class PointCloudData : ScriptableObject
  9. {
  10. #region Public properties
  11. /// Byte size of the point element.
  12. public const int elementSize = sizeof(float) * 4;
  13. /// Number of points.
  14. public int pointCount {
  15. get { return _pointData.Length; }
  16. }
  17. /// Get access to the compute buffer that contains the point cloud.
  18. public ComputeBuffer computeBuffer {
  19. get {
  20. if (_pointBuffer == null)
  21. {
  22. _pointBuffer = new ComputeBuffer(pointCount, elementSize);
  23. _pointBuffer.SetData(_pointData);
  24. }
  25. return _pointBuffer;
  26. }
  27. }
  28. #endregion
  29. #region ScriptableObject implementation
  30. ComputeBuffer _pointBuffer;
  31. void OnDisable()
  32. {
  33. if (_pointBuffer != null)
  34. {
  35. _pointBuffer.Release();
  36. _pointBuffer = null;
  37. }
  38. }
  39. #endregion
  40. #region Serialized data members
  41. [System.Serializable]
  42. struct Point
  43. {
  44. public Vector3 position;
  45. public uint color;
  46. }
  47. [SerializeField] Point[] _pointData;
  48. #endregion
  49. static uint EncodeColor(Color c)
  50. {
  51. const float kMaxBrightness = 16;
  52. var y = Mathf.Max(Mathf.Max(c.r, c.g), c.b);
  53. y = Mathf.Clamp(Mathf.Ceil(y * 255 / kMaxBrightness), 1, 255);
  54. var rgb = new Vector3(c.r, c.g, c.b);
  55. rgb *= 255 * 255 / (y * kMaxBrightness);
  56. return ((uint)rgb.x ) |
  57. ((uint)rgb.y << 8) |
  58. ((uint)rgb.z << 16) |
  59. ((uint)y << 24);
  60. }
  61. public void Initialize(IList<Vector3> positions, IList<Color32> colors)
  62. {
  63. _pointData = new Point[positions.Count];
  64. for (var i = 0; i < _pointData.Length; i++)
  65. {
  66. _pointData[i] = new Point {
  67. position = positions[i],
  68. color = EncodeColor(colors[i])
  69. };
  70. }
  71. }
  72. }
  73. }