No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ImagePacker.cs 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. //#define PACKING_DEBUG
  2. using System;
  3. using Unity.Burst;
  4. using Unity.Mathematics;
  5. using UnityEngine;
  6. using Unity.Collections;
  7. using Unity.Collections.LowLevel.Unsafe;
  8. namespace UnityEditor.U2D.Common
  9. {
  10. [BurstCompile]
  11. internal static class ImagePacker
  12. {
  13. /// <summary>
  14. /// Given an array of rects, the method returns an array of rects arranged within outPackedWidth and outPackedHeight
  15. /// </summary>
  16. /// <param name="rects">Rects to pack</param>
  17. /// <param name="padding">Padding between each rect</param>
  18. /// <param name="outPackedRects">Rects arranged within outPackedWidth and outPackedHeight</param>
  19. /// <param name="outPackedWidth">Width of the packed rects</param>
  20. /// <param name="outPackedHeight">Height of the packed rects</param>
  21. public static void Pack(RectInt[] rects, int padding, out RectInt[] outPackedRects, out int outPackedWidth, out int outPackedHeight, bool requireSquarePOT = false)
  22. {
  23. var packNode = InternalPack(rects, padding, requireSquarePOT);
  24. outPackedWidth = packNode.rect.width;
  25. outPackedHeight = packNode.rect.height;
  26. var visitor = new CollectPackNodePositionVisitor();
  27. packNode.AcceptVisitor(visitor);
  28. outPackedRects = new RectInt[rects.Length];
  29. for (int i = 0; i < rects.Length; ++i)
  30. outPackedRects[i] = new RectInt(visitor.positions[i].x + padding, visitor.positions[i].y + padding, rects[i].width, rects[i].height);
  31. #if PACKING_DEBUG
  32. var emptyNodeCollector = new CollectEmptyNodePositionVisitor();
  33. packNode.AcceptVisitor(emptyNodeCollector);
  34. Array.Resize(ref outPackedRects, rects.Length + emptyNodeCollector.emptyAreas.Count);
  35. for (int i = rects.Length; i < outPackedRects.Length; ++i)
  36. outPackedRects[i] = emptyNodeCollector.emptyAreas[i - rects.Length];
  37. #endif
  38. }
  39. /// <summary>
  40. /// Packs image buffer into a single buffer. Image buffers are assumed to be 4 bytes per pixel in RGBA format
  41. /// </summary>
  42. /// <param name="buffers">Image buffers to pack</param>
  43. /// <param name="width">Image buffers width</param>
  44. /// <param name="height">Image buffers height</param>
  45. /// <param name="padding">Padding between each packed image</param>
  46. /// <param name="spriteSizeExpand">Pack sprite expand size</param>
  47. /// <param name="outPackedBuffer">Packed image buffer</param>
  48. /// <param name="outPackedBufferWidth">Packed image buffer's width</param>
  49. /// <param name="outPackedBufferHeight">Packed image buffer's height</param>
  50. /// <param name="outPackedRect">Location of each image buffers in the packed buffer</param>
  51. /// <param name="outUVTransform">Translation data from image original buffer to packed buffer</param>
  52. public static void Pack(NativeArray<Color32>[] buffers, int[] width, int[] height, int padding, uint spriteSizeExpand, out NativeArray<Color32> outPackedBuffer, out int outPackedBufferWidth, out int outPackedBufferHeight, out RectInt[] outPackedRect, out Vector2Int[] outUVTransform, bool requireSquarePOT = false)
  53. {
  54. UnityEngine.Profiling.Profiler.BeginSample("Pack");
  55. // Determine the area that contains data in the buffer
  56. outPackedBuffer = default(NativeArray<Color32>);
  57. try
  58. {
  59. var tightRects = FindTightRectJob.Execute(buffers, width, height);
  60. var tightRectArea = new RectInt[tightRects.Length];
  61. for (var i = 0; i < tightRects.Length; ++i)
  62. {
  63. var t = tightRects[i];
  64. t.width = tightRects[i].width + (int)spriteSizeExpand;
  65. t.height = tightRects[i].height + (int)spriteSizeExpand;
  66. tightRectArea[i] = t;
  67. }
  68. Pack(tightRectArea, padding, out outPackedRect, out outPackedBufferWidth, out outPackedBufferHeight, requireSquarePOT);
  69. var packBufferSize = (ulong)outPackedBufferWidth * (ulong)outPackedBufferHeight;
  70. if (packBufferSize < 0 || packBufferSize >= int.MaxValue)
  71. {
  72. throw new ArgumentException("Unable to create pack texture. Image size is too big to pack.");
  73. }
  74. outUVTransform = new Vector2Int[tightRectArea.Length];
  75. for (var i = 0; i < outUVTransform.Length; ++i)
  76. {
  77. outUVTransform[i] = new Vector2Int(outPackedRect[i].x - tightRects[i].x, outPackedRect[i].y - tightRects[i].y);
  78. }
  79. outPackedBuffer = new NativeArray<Color32>(outPackedBufferWidth * outPackedBufferHeight, Allocator.Persistent);
  80. Blit(outPackedBuffer, outPackedRect, outPackedBufferWidth, buffers, tightRects, width, padding);
  81. }
  82. catch (Exception ex)
  83. {
  84. if (outPackedBuffer.IsCreated)
  85. outPackedBuffer.Dispose();
  86. throw ex;
  87. }
  88. finally
  89. {
  90. UnityEngine.Profiling.Profiler.EndSample();
  91. }
  92. }
  93. static ImagePackNode InternalPack(RectInt[] rects, int padding, bool requireSquarePOT = false)
  94. {
  95. if (rects == null || rects.Length == 0)
  96. return new ImagePackNode() { rect = new RectInt(0, 0, 0, 0)};
  97. var sortedRects = new ImagePackRect[rects.Length];
  98. for (int i = 0; i < rects.Length; ++i)
  99. {
  100. sortedRects[i] = new ImagePackRect();
  101. sortedRects[i].rect = rects[i];
  102. sortedRects[i].index = i;
  103. }
  104. var initialWidth = (int)NextPowerOfTwo((ulong)rects[0].width);
  105. var initialHeight = (int)NextPowerOfTwo((ulong)rects[0].height);
  106. if (requireSquarePOT)
  107. initialWidth = initialHeight = (initialWidth > initialHeight) ? initialWidth : initialHeight;
  108. Array.Sort<ImagePackRect>(sortedRects);
  109. var root = new ImagePackNode();
  110. root.rect = new RectInt(0, 0, initialWidth, initialHeight);
  111. for (int i = 0; i < rects.Length; ++i)
  112. {
  113. if (!root.Insert(sortedRects[i], padding)) // we can't fit
  114. {
  115. int newWidth = root.rect.width , newHeight = root.rect.height;
  116. if (root.rect.width < root.rect.height)
  117. {
  118. newWidth = (int)NextPowerOfTwo((ulong)root.rect.width + 1);
  119. // Every time height changes, we reset height to grow again.
  120. newHeight = initialHeight;
  121. }
  122. else
  123. newHeight = (int)NextPowerOfTwo((ulong)root.rect.height + 1);
  124. if (requireSquarePOT)
  125. newWidth = newHeight = (newWidth > newHeight) ? newWidth : newHeight;
  126. // Reset all packing and try again
  127. root = new ImagePackNode();
  128. root.rect = new RectInt(0, 0, newWidth, newHeight);
  129. i = -1;
  130. }
  131. }
  132. return root;
  133. }
  134. public static void Blit(NativeArray<Color32> buffer, RectInt[] blitToArea, int bufferBytesPerRow, NativeArray<Color32>[] originalBuffer, RectInt[] blitFromArea, int[] bytesPerRow, int padding)
  135. {
  136. UnityEngine.Profiling.Profiler.BeginSample("Blit");
  137. for (var bufferIndex = 0; bufferIndex < blitToArea.Length && bufferIndex < originalBuffer.Length && bufferIndex < blitFromArea.Length; ++bufferIndex)
  138. {
  139. var fromArea = new int4(blitFromArea[bufferIndex].x, blitFromArea[bufferIndex].y, blitFromArea[bufferIndex].width, blitFromArea[bufferIndex].height);
  140. var toArea = new int4(blitToArea[bufferIndex].x, blitToArea[bufferIndex].y, blitToArea[bufferIndex].width, blitToArea[bufferIndex].height);
  141. BurstedBlit(originalBuffer[bufferIndex], in fromArea, in toArea, bytesPerRow[bufferIndex], bufferBytesPerRow, ref buffer);
  142. }
  143. #if PACKING_DEBUG
  144. var emptyColors = new Color32[]
  145. {
  146. new Color32((byte)255, (byte)0, (byte)0, (byte)255),
  147. new Color32((byte)255, (byte)255, (byte)0, (byte)255),
  148. new Color32((byte)255, (byte)0, (byte)255, (byte)255),
  149. new Color32((byte)255, (byte)255, (byte)255, (byte)255),
  150. new Color32((byte)0, (byte)255, (byte)0, (byte)255),
  151. new Color32((byte)0, (byte)0, (byte)255, (byte)255)
  152. };
  153. for (int k = originalBuffer.Length; k < blitToArea.Length; ++k)
  154. {
  155. var rectFrom = blitToArea[k];
  156. for (int i = 0; i < rectFrom.height; ++i)
  157. {
  158. for (int j = 0; j < rectFrom.width; ++j)
  159. {
  160. c[((rectFrom.y + i) * bufferbytesPerRow) + rectFrom.x + j] =
  161. emptyColors[k % emptyColors.Length];
  162. }
  163. }
  164. }
  165. #endif
  166. UnityEngine.Profiling.Profiler.EndSample();
  167. }
  168. [BurstCompile]
  169. static unsafe void BurstedBlit(in NativeArray<Color32> originalBuffer, in int4 rectFrom, in int4 rectTo, int bytesPerRow, int bufferBytesPerRow, ref NativeArray<Color32> buffer)
  170. {
  171. var c = (Color32*)buffer.GetUnsafePtr();
  172. var b = (Color32*)originalBuffer.GetUnsafeReadOnlyPtr();
  173. var toXStart = (int)(rectTo.z * 0.5f - rectFrom.z * 0.5f);
  174. var toYStart = (int)(rectTo.w * 0.5f - rectFrom.w * 0.5f);
  175. toXStart = toXStart <= 0 ? rectTo.x : toXStart + rectTo.x;
  176. toYStart = toYStart <= 0 ? rectTo.y : toYStart + rectTo.y;
  177. for (var i = 0; i < rectFrom.w && i < rectTo.w; ++i)
  178. {
  179. for (var j = 0; j < rectFrom.z && j < rectTo.z; ++j)
  180. {
  181. var cc = b[(rectFrom.y + i) * bytesPerRow + rectFrom.x + j];
  182. c[((toYStart + i) * bufferBytesPerRow) + toXStart + j] = cc;
  183. }
  184. }
  185. }
  186. internal static ulong NextPowerOfTwo(ulong v)
  187. {
  188. v -= 1;
  189. v |= v >> 16;
  190. v |= v >> 8;
  191. v |= v >> 4;
  192. v |= v >> 2;
  193. v |= v >> 1;
  194. return v + 1;
  195. }
  196. internal class ImagePackRect : IComparable<ImagePackRect>
  197. {
  198. public RectInt rect;
  199. public int index;
  200. public int CompareTo(ImagePackRect obj)
  201. {
  202. var lhsArea = rect.width * rect.height;
  203. var rhsArea = obj.rect.width * obj.rect.height;
  204. if (lhsArea > rhsArea)
  205. return -1;
  206. if (lhsArea < rhsArea)
  207. return 1;
  208. if (index < obj.index)
  209. return -1;
  210. return 1;
  211. }
  212. }
  213. }
  214. }