Region.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. #nullable enable
  2. namespace Terminal.Gui;
  3. using System.Buffers;
  4. /// <summary>
  5. /// Represents a region composed of one or more rectangles, providing methods for union, intersection, exclusion, and
  6. /// complement operations.
  7. /// </summary>
  8. public class Region : IDisposable
  9. {
  10. private List<Rectangle> _rectangles;
  11. /// <summary>
  12. /// Initializes a new instance of the <see cref="Region"/> class.
  13. /// </summary>
  14. public Region () { _rectangles = new (); }
  15. /// <summary>
  16. /// Initializes a new instance of the <see cref="Region"/> class with the specified rectangle.
  17. /// </summary>
  18. /// <param name="rectangle">The initial rectangle for the region.</param>
  19. public Region (Rectangle rectangle) { _rectangles = new () { rectangle }; }
  20. /// <summary>
  21. /// Adds the specified rectangle to the region.
  22. /// </summary>
  23. /// <param name="rectangle">The rectangle to add to the region.</param>
  24. public void Union (Rectangle rectangle)
  25. {
  26. _rectangles.Add (rectangle);
  27. _rectangles = MergeRectangles (_rectangles);
  28. }
  29. /// <summary>
  30. /// Adds the specified region to this region.
  31. /// </summary>
  32. /// <param name="region">The region to add to this region.</param>
  33. public void Union (Region region)
  34. {
  35. _rectangles.AddRange (region._rectangles);
  36. _rectangles = MergeRectangles (_rectangles);
  37. }
  38. /// <summary>
  39. /// Updates the region to be the intersection of itself with the specified rectangle.
  40. /// </summary>
  41. /// <param name="rectangle">The rectangle to intersect with the region.</param>
  42. public void Intersect (Rectangle rectangle)
  43. {
  44. if (_rectangles.Count == 0)
  45. {
  46. return;
  47. }
  48. // TODO: In-place swap within the original list. Does order of intersections matter?
  49. // Rectangle = 4 * i32 = 16 B
  50. // ~128 B stack allocation
  51. const int maxStackallocLength = 8;
  52. Rectangle []? rentedArray = null;
  53. try
  54. {
  55. Span<Rectangle> rectBuffer = _rectangles.Count <= maxStackallocLength
  56. ? stackalloc Rectangle[maxStackallocLength]
  57. : (rentedArray = ArrayPool<Rectangle>.Shared.Rent (_rectangles.Count));
  58. _rectangles.CopyTo (rectBuffer);
  59. ReadOnlySpan<Rectangle> rectangles = rectBuffer[.._rectangles.Count];
  60. _rectangles.Clear ();
  61. foreach (var rect in rectangles)
  62. {
  63. Rectangle intersection = Rectangle.Intersect (rect, rectangle);
  64. if (!intersection.IsEmpty)
  65. {
  66. _rectangles.Add (intersection);
  67. }
  68. }
  69. }
  70. finally
  71. {
  72. if (rentedArray != null)
  73. {
  74. ArrayPool<Rectangle>.Shared.Return (rentedArray);
  75. }
  76. }
  77. }
  78. /// <summary>
  79. /// Updates the region to be the intersection of itself with the specified region.
  80. /// </summary>
  81. /// <param name="region">The region to intersect with this region.</param>
  82. public void Intersect (Region region)
  83. {
  84. List<Rectangle> intersections = new List<Rectangle> ();
  85. foreach (Rectangle rect1 in _rectangles)
  86. {
  87. foreach (Rectangle rect2 in region._rectangles)
  88. {
  89. Rectangle intersected = Rectangle.Intersect (rect1, rect2);
  90. if (!intersected.IsEmpty)
  91. {
  92. intersections.Add (intersected);
  93. }
  94. }
  95. }
  96. _rectangles = intersections;
  97. }
  98. /// <summary>
  99. /// Removes the specified rectangle from the region.
  100. /// </summary>
  101. /// <param name="rectangle">The rectangle to exclude from the region.</param>
  102. public void Exclude (Rectangle rectangle) { _rectangles = _rectangles.SelectMany (r => SubtractRectangle (r, rectangle)).ToList (); }
  103. /// <summary>
  104. /// Removes the portion of the specified region from this region.
  105. /// </summary>
  106. /// <param name="region">The region to exclude from this region.</param>
  107. public void Exclude (Region region)
  108. {
  109. foreach (Rectangle rect in region._rectangles)
  110. {
  111. _rectangles = _rectangles.SelectMany (r => SubtractRectangle (r, rect)).ToList ();
  112. }
  113. }
  114. /// <summary>
  115. /// Updates the region to be the complement of itself within the specified bounds.
  116. /// </summary>
  117. /// <param name="bounds">The bounding rectangle to use for complementing the region.</param>
  118. public void Complement (Rectangle bounds)
  119. {
  120. if (bounds.IsEmpty || _rectangles.Count == 0)
  121. {
  122. _rectangles.Clear ();
  123. return;
  124. }
  125. List<Rectangle> complementRectangles = new List<Rectangle> { bounds };
  126. foreach (Rectangle rect in _rectangles)
  127. {
  128. complementRectangles = complementRectangles.SelectMany (r => SubtractRectangle (r, rect)).ToList ();
  129. }
  130. _rectangles = complementRectangles;
  131. }
  132. /// <summary>
  133. /// Creates an exact copy of the region.
  134. /// </summary>
  135. /// <returns>A new <see cref="Region"/> that is a copy of this instance.</returns>
  136. public Region Clone ()
  137. {
  138. var clone = new Region ();
  139. clone._rectangles = new (_rectangles);
  140. return clone;
  141. }
  142. /// <summary>
  143. /// Gets a bounding rectangle for the entire region.
  144. /// </summary>
  145. /// <returns>A <see cref="Rectangle"/> that bounds the region.</returns>
  146. public Rectangle GetBounds ()
  147. {
  148. if (_rectangles.Count == 0)
  149. {
  150. return Rectangle.Empty;
  151. }
  152. int left = _rectangles.Min (r => r.Left);
  153. int top = _rectangles.Min (r => r.Top);
  154. int right = _rectangles.Max (r => r.Right);
  155. int bottom = _rectangles.Max (r => r.Bottom);
  156. return new (left, top, right - left, bottom - top);
  157. }
  158. /// <summary>
  159. /// Determines whether the region is empty.
  160. /// </summary>
  161. /// <returns><c>true</c> if the region is empty; otherwise, <c>false</c>.</returns>
  162. public bool IsEmpty () { return !_rectangles.Any (); }
  163. /// <summary>
  164. /// Determines whether the specified point is contained within the region.
  165. /// </summary>
  166. /// <param name="x">The x-coordinate of the point.</param>
  167. /// <param name="y">The y-coordinate of the point.</param>
  168. /// <returns><c>true</c> if the point is contained within the region; otherwise, <c>false</c>.</returns>
  169. public bool Contains (int x, int y)
  170. {
  171. foreach (var rect in _rectangles)
  172. {
  173. if (rect.Contains (x, y))
  174. {
  175. return true;
  176. }
  177. }
  178. return false;
  179. }
  180. /// <summary>
  181. /// Determines whether the specified rectangle is contained within the region.
  182. /// </summary>
  183. /// <param name="rectangle">The rectangle to check for containment.</param>
  184. /// <returns><c>true</c> if the rectangle is contained within the region; otherwise, <c>false</c>.</returns>
  185. public bool Contains (Rectangle rectangle)
  186. {
  187. foreach (var rect in _rectangles)
  188. {
  189. if (rect.Contains (rectangle))
  190. {
  191. return true;
  192. }
  193. }
  194. return false;
  195. }
  196. /// <summary>
  197. /// Returns an array of rectangles that represent the region.
  198. /// </summary>
  199. /// <returns>An array of <see cref="Rectangle"/> objects that make up the region.</returns>
  200. public Rectangle [] GetRegionScans () { return _rectangles.ToArray (); }
  201. /// <summary>
  202. /// Offsets all rectangles in the region by the specified amounts.
  203. /// </summary>
  204. /// <param name="offsetX">The amount to offset along the x-axis.</param>
  205. /// <param name="offsetY">The amount to offset along the y-axis.</param>
  206. public void Offset (int offsetX, int offsetY)
  207. {
  208. for (int i = 0; i < _rectangles.Count; i++)
  209. {
  210. var rect = _rectangles [i];
  211. _rectangles [i] = new Rectangle (rect.Left + offsetX, rect.Top + offsetY, rect.Width, rect.Height);
  212. }
  213. }
  214. /// <summary>
  215. /// Merges overlapping rectangles into a minimal set of non-overlapping rectangles.
  216. /// </summary>
  217. /// <param name="rectangles">The list of rectangles to merge.</param>
  218. /// <returns>A list of merged rectangles.</returns>
  219. private List<Rectangle> MergeRectangles (List<Rectangle> rectangles)
  220. {
  221. // Simplified merging logic: this does not handle all edge cases for merging overlapping rectangles.
  222. // For a full implementation, a plane sweep algorithm or similar would be needed.
  223. List<Rectangle> merged = new List<Rectangle> (rectangles);
  224. bool mergedAny;
  225. do
  226. {
  227. mergedAny = false;
  228. for (var i = 0; i < merged.Count; i++)
  229. {
  230. for (int j = i + 1; j < merged.Count; j++)
  231. {
  232. if (merged [i].IntersectsWith (merged [j]))
  233. {
  234. merged [i] = Rectangle.Union (merged [i], merged [j]);
  235. merged.RemoveAt (j);
  236. mergedAny = true;
  237. break;
  238. }
  239. }
  240. if (mergedAny)
  241. {
  242. break;
  243. }
  244. }
  245. }
  246. while (mergedAny);
  247. return merged;
  248. }
  249. /// <summary>
  250. /// Subtracts the specified rectangle from the original rectangle, returning the resulting rectangles.
  251. /// </summary>
  252. /// <param name="original">The original rectangle.</param>
  253. /// <param name="subtract">The rectangle to subtract from the original.</param>
  254. /// <returns>An enumerable collection of resulting rectangles after subtraction.</returns>
  255. private IEnumerable<Rectangle> SubtractRectangle (Rectangle original, Rectangle subtract)
  256. {
  257. if (!original.IntersectsWith (subtract))
  258. {
  259. yield return original;
  260. yield break;
  261. }
  262. // Top segment
  263. if (original.Top < subtract.Top)
  264. {
  265. yield return new (original.Left, original.Top, original.Width, subtract.Top - original.Top);
  266. }
  267. // Bottom segment
  268. if (original.Bottom > subtract.Bottom)
  269. {
  270. yield return new (original.Left, subtract.Bottom, original.Width, original.Bottom - subtract.Bottom);
  271. }
  272. // Left segment
  273. if (original.Left < subtract.Left)
  274. {
  275. int top = Math.Max (original.Top, subtract.Top);
  276. int bottom = Math.Min (original.Bottom, subtract.Bottom);
  277. if (bottom > top)
  278. {
  279. yield return new (original.Left, top, subtract.Left - original.Left, bottom - top);
  280. }
  281. }
  282. // Right segment
  283. if (original.Right > subtract.Right)
  284. {
  285. int top = Math.Max (original.Top, subtract.Top);
  286. int bottom = Math.Min (original.Bottom, subtract.Bottom);
  287. if (bottom > top)
  288. {
  289. yield return new (subtract.Right, top, original.Right - subtract.Right, bottom - top);
  290. }
  291. }
  292. }
  293. /// <summary>
  294. /// Releases all resources used by the <see cref="Region"/>.
  295. /// </summary>
  296. public void Dispose () { _rectangles.Clear (); }
  297. }