InfraredSourceManager.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using UnityEngine;
  2. using System.Collections;
  3. using Windows.Kinect;
  4. public class InfraredSourceManager : MonoBehaviour
  5. {
  6. private KinectSensor _Sensor;
  7. private InfraredFrameReader _Reader;
  8. private ushort[] _Data;
  9. private byte[] _RawData;
  10. // I'm not sure this makes sense for the Kinect APIs
  11. // Instead, this logic should be in the VIEW
  12. private Texture2D _Texture;
  13. public Texture2D GetInfraredTexture()
  14. {
  15. return _Texture;
  16. }
  17. void Start()
  18. {
  19. _Sensor = KinectSensor.GetDefault();
  20. if (_Sensor != null)
  21. {
  22. _Reader = _Sensor.InfraredFrameSource.OpenReader();
  23. var frameDesc = _Sensor.InfraredFrameSource.FrameDescription;
  24. _Data = new ushort[frameDesc.LengthInPixels];
  25. _RawData = new byte[frameDesc.LengthInPixels * 4];
  26. _Texture = new Texture2D(frameDesc.Width, frameDesc.Height, TextureFormat.BGRA32, false);
  27. if (!_Sensor.IsOpen)
  28. {
  29. _Sensor.Open();
  30. }
  31. }
  32. }
  33. void Update ()
  34. {
  35. if (_Reader != null)
  36. {
  37. var frame = _Reader.AcquireLatestFrame();
  38. if (frame != null)
  39. {
  40. frame.CopyFrameDataToArray(_Data);
  41. int index = 0;
  42. foreach(var ir in _Data)
  43. {
  44. byte intensity = (byte)(ir >> 8);
  45. _RawData[index++] = intensity;
  46. _RawData[index++] = intensity;
  47. _RawData[index++] = intensity;
  48. _RawData[index++] = 255; // Alpha
  49. }
  50. _Texture.LoadRawTextureData(_RawData);
  51. _Texture.Apply();
  52. frame.Dispose();
  53. frame = null;
  54. }
  55. }
  56. }
  57. void OnApplicationQuit()
  58. {
  59. if (_Reader != null)
  60. {
  61. _Reader.Dispose();
  62. _Reader = null;
  63. }
  64. if (_Sensor != null)
  65. {
  66. if (_Sensor.IsOpen)
  67. {
  68. _Sensor.Close();
  69. }
  70. _Sensor = null;
  71. }
  72. }
  73. }