FindTightRectJob.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System;
  2. using UnityEngine;
  3. using Unity.Collections;
  4. using Unity.Collections.LowLevel.Unsafe;
  5. using Unity.Jobs;
  6. namespace UnityEditor.U2D.Common
  7. {
  8. public struct FindTightRectJob : IJobParallelFor
  9. {
  10. [ReadOnly]
  11. [DeallocateOnJobCompletion]
  12. NativeArray<IntPtr> m_Buffers;
  13. [ReadOnly]
  14. int m_Width;
  15. [ReadOnly]
  16. int m_Height;
  17. NativeArray<RectInt> m_Output;
  18. public unsafe void Execute(int index)
  19. {
  20. var rect = new RectInt(m_Width, m_Height, 0, 0);
  21. var color = (Color32*)m_Buffers[index].ToPointer();
  22. for (int i = 0; i < m_Height; ++i)
  23. {
  24. for (int j = 0; j < m_Width; ++j)
  25. {
  26. if (color->a != 0)
  27. {
  28. rect.x = Mathf.Min(j, rect.x);
  29. rect.y = Mathf.Min(i, rect.y);
  30. rect.width = Mathf.Max(j, rect.width);
  31. rect.height = Mathf.Max(i, rect.height);
  32. }
  33. ++color;
  34. }
  35. }
  36. rect.width = Mathf.Max(0, rect.width - rect.x + 1);
  37. rect.height = Mathf.Max(0, rect.height - rect.y + 1);
  38. m_Output[index] = rect;
  39. }
  40. public static unsafe RectInt[] Execute(NativeArray<Color32>[] buffers, int width, int height)
  41. {
  42. var job = new FindTightRectJob();
  43. job.m_Buffers = new NativeArray<IntPtr>(buffers.Length, Allocator.TempJob);
  44. for (int i = 0; i < buffers.Length; ++i)
  45. job.m_Buffers[i] = new IntPtr(buffers[i].GetUnsafeReadOnlyPtr());
  46. job.m_Output = new NativeArray<RectInt>(buffers.Length, Allocator.TempJob);
  47. job.m_Width = width;
  48. job.m_Height = height;
  49. // Ensure all jobs are completed before we return since we don't own the buffers
  50. job.Schedule(buffers.Length, 1).Complete();
  51. var rects = job.m_Output.ToArray();
  52. job.m_Output.Dispose();
  53. return rects;
  54. }
  55. }
  56. }