Ingen beskrivning
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.

NativeSort.cs 59KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using Unity.Burst;
  5. using Unity.Collections.LowLevel.Unsafe;
  6. using Unity.Jobs;
  7. using Unity.Jobs.LowLevel.Unsafe;
  8. using Unity.Mathematics;
  9. namespace Unity.Collections
  10. {
  11. /// <summary>
  12. /// Extension methods for sorting collections.
  13. /// </summary>
  14. [BurstCompatible]
  15. public static class NativeSortExtension
  16. {
  17. /// <summary>
  18. /// A comparer that uses IComparable.CompareTo(). For primitive types, this is an ascending sort.
  19. /// </summary>
  20. /// <typeparam name="T">Source type of elements</typeparam>
  21. [BurstCompatible(GenericTypeArguments = new[] { typeof(int) })]
  22. public struct DefaultComparer<T> : IComparer<T> where T : IComparable<T>
  23. {
  24. /// <summary>
  25. /// Compares two values.
  26. /// </summary>
  27. /// <param name="x">First value to compare.</param>
  28. /// <param name="y">Second value to compare.</param>
  29. /// <returns>A signed integer that denotes the relative values of `x` and `y`:
  30. /// 0 if they're equal, negative if `x &lt; y`, and positive if `x &gt; y`.</returns>
  31. public int Compare(T x, T y) => x.CompareTo(y);
  32. }
  33. /// <summary>
  34. /// Sorts an array in ascending order.
  35. /// </summary>
  36. /// <typeparam name="T">The type of the elements.</typeparam>
  37. /// <param name="array">The array to sort.</param>
  38. /// <param name="length">The number of elements to sort in the array.
  39. /// Indexes greater than or equal to `length` won't be included in the sort.</param>
  40. [BurstCompatible(GenericTypeArguments = new[] { typeof(int) })]
  41. public unsafe static void Sort<T>(T* array, int length)
  42. where T : unmanaged, IComparable<T>
  43. {
  44. IntroSort<T, DefaultComparer<T>>(array, length, new DefaultComparer<T>());
  45. }
  46. /// <summary>
  47. /// Sorts an array using a custom comparison.
  48. /// </summary>
  49. /// <typeparam name="T">The type of the elements.</typeparam>
  50. /// <typeparam name="U">The type of the comparer.</typeparam>
  51. /// <param name="array">The array to sort.</param>
  52. /// <param name="length">The number of elements to sort in the array.
  53. /// Indexes greater than or equal to `length` won't be included in the sort.</param>
  54. /// <param name="comp">The comparison function used to determine the relative order of the elements.</param>
  55. [BurstCompatible(GenericTypeArguments = new[] { typeof(int), typeof(DefaultComparer<int>) })]
  56. public unsafe static void Sort<T, U>(T* array, int length, U comp)
  57. where T : unmanaged
  58. where U : IComparer<T>
  59. {
  60. IntroSort<T, U>(array, length, comp);
  61. }
  62. /// <summary>
  63. /// Creates and schedules a job that will sort an array in ascending order.
  64. /// </summary>
  65. /// <typeparam name="T">The type of elements.</typeparam>
  66. /// <param name="array">The array to sort.</param>
  67. /// <param name="length">The number of elements to sort in the array.
  68. /// Indexes greater than or equal to `length` won't be included in the sort.</param>
  69. /// <param name="inputDeps">A job handle which the newly created job will depend upon.</param>
  70. /// <returns>The handle of the new job which will sort the array.</returns>
  71. [NotBurstCompatible /* This is not burst compatible because of IJob's use of a static IntPtr. Should switch to IJobBurstSchedulable in the future */]
  72. [Obsolete("Instead call SortJob(T*, int).Schedule(JobHandle). (RemovedAfter 2021-06-20)", false)]
  73. public unsafe static JobHandle Sort<T>(T* array, int length, JobHandle inputDeps)
  74. where T : unmanaged, IComparable<T>
  75. {
  76. return Sort(array, length, new DefaultComparer<T>(), inputDeps);
  77. }
  78. /// <summary>
  79. /// Returns a job which will sort an array in ascending order.
  80. /// </summary>
  81. /// <remarks>This method does not schedule the job. Scheduling the job is left to you.</remarks>
  82. /// <typeparam name="T">The type of the elements.</typeparam>
  83. /// <param name="array">The array to sort.</param>
  84. /// <param name="length">The number of elements to sort in the array.
  85. /// Indexes greater than or equal to `length` won't be included in the sort.</param>
  86. /// <returns>A job for sorting the array.</returns>
  87. [BurstCompatible(GenericTypeArguments = new[] { typeof(int) }, RequiredUnityDefine = "UNITY_2020_2_OR_NEWER" /* Due to job scheduling on 2020.1 using statics */)]
  88. public unsafe static SortJob<T, DefaultComparer<T>> SortJob<T>(T* array, int length)
  89. where T : unmanaged, IComparable<T>
  90. {
  91. return new SortJob<T, DefaultComparer<T>> {Data = array, Length = length, Comp = new DefaultComparer<T>()};
  92. }
  93. /// <summary>
  94. /// Sorts an array using a custom comparison function.
  95. /// </summary>
  96. /// <typeparam name="T">Source type of elements</typeparam>
  97. /// <typeparam name="U">The comparer type.</typeparam>
  98. /// <param name="array">Array to perform sort.</param>
  99. /// <param name="length">Number of elements to perform sort.</param>
  100. /// <param name="comp">A comparison function that determines whether one element in the array is less than, equal to, or greater than another element.</param>
  101. /// <param name="inputDeps">The job handle or handles for any scheduled jobs that use this container.</param>
  102. /// <returns>A new job handle containing the prior handles as well as the handle for the job that sorts
  103. /// the container.</returns>
  104. [NotBurstCompatible /* This is not burst compatible because of IJob's use of a static IntPtr. Should switch to IJobBurstSchedulable in the future */]
  105. [Obsolete("Instead call SortJob(T*, int, U).Schedule(JobHandle). (RemovedAfter 2021-06-20)", false)]
  106. public unsafe static JobHandle Sort<T, U>(T* array, int length, U comp, JobHandle inputDeps)
  107. where T : unmanaged
  108. where U : IComparer<T>
  109. {
  110. if (length == 0)
  111. {
  112. return inputDeps;
  113. }
  114. var segmentCount = (length + 1023) / 1024;
  115. var workerCount = math.max(1, JobsUtility.MaxJobThreadCount);
  116. var workerSegmentCount = segmentCount / workerCount;
  117. var segmentSortJob = new SegmentSort<T, U> { Data = array, Comp = comp, Length = length, SegmentWidth = 1024 };
  118. var segmentSortJobHandle = segmentSortJob.Schedule(segmentCount, workerSegmentCount, inputDeps);
  119. var segmentSortMergeJob = new SegmentSortMerge<T, U> { Data = array, Comp = comp, Length = length, SegmentWidth = 1024 };
  120. var segmentSortMergeJobHandle = segmentSortMergeJob.Schedule(segmentSortJobHandle);
  121. return segmentSortMergeJobHandle;
  122. }
  123. /// <summary>
  124. /// Returns a job which will sort an array using a custom comparison.
  125. /// </summary>
  126. /// <remarks>This method does not schedule the job. Scheduling the job is left to you.</remarks>
  127. /// <typeparam name="T">The type of the elements.</typeparam>
  128. /// <typeparam name="U">The type of the comparer.</typeparam>
  129. /// <param name="array">The array to sort.</param>
  130. /// <param name="length">The number of elements to sort in the array.
  131. /// Indexes greater than or equal to `length` won't be included in the sort.</param>
  132. /// <param name="comp">The comparison function used to determine the relative order of the elements.</param>
  133. /// <returns>A job for sorting the array.</returns>
  134. [BurstCompatible(GenericTypeArguments = new[] { typeof(int), typeof(DefaultComparer<int>) }, RequiredUnityDefine = "UNITY_2020_2_OR_NEWER" /* Due to job scheduling on 2020.1 using statics */)]
  135. public unsafe static SortJob<T, U> SortJob<T, U>(T* array, int length, U comp)
  136. where T : unmanaged
  137. where U : IComparer<T>
  138. {
  139. return new SortJob<T, U>() {Data = array, Length = length, Comp = comp};
  140. }
  141. /// <summary>
  142. /// Finds a value in a sorted array by binary search.
  143. /// </summary>
  144. /// <remarks>If the array is not sorted, the value might not be found, even if it's present in the array.</remarks>
  145. /// <typeparam name="T">The type of the elements.</typeparam>
  146. /// <param name="ptr">The array to search.</param>
  147. /// <param name="value">The value to locate.</param>
  148. /// <param name="length">The number of elements to search. Indexes greater than or equal to `length` won't be searched.</param>
  149. /// <returns>If found, the index of the located value. If not found, the return value is negative.</returns>
  150. [BurstCompatible(GenericTypeArguments = new[] { typeof(int) })]
  151. public unsafe static int BinarySearch<T>(T* ptr, int length, T value)
  152. where T : unmanaged, IComparable<T>
  153. {
  154. return BinarySearch(ptr, length, value, new DefaultComparer<T>());
  155. }
  156. /// <summary>
  157. /// Finds a value in a sorted array by binary search using a custom comparison.
  158. /// </summary>
  159. /// <remarks>If the array is not sorted, the value might not be found, even if it's present in the array.</remarks>
  160. /// <typeparam name="T">The type of the elements.</typeparam>
  161. /// <typeparam name="U">The type of the comparer.</typeparam>
  162. /// <param name="ptr">The array to search.</param>
  163. /// <param name="value">The value to locate.</param>
  164. /// <param name="length">The number of elements to search. Indexes greater than or equal to `length` won't be searched.</param>
  165. /// <param name="comp">The comparison function used to determine the relative order of the elements.</param>
  166. /// <returns>If found, the index of the located value. If not found, the return value is negative.</returns>
  167. [BurstCompatible(GenericTypeArguments = new[] { typeof(int), typeof(DefaultComparer<int>) })]
  168. public unsafe static int BinarySearch<T, U>(T* ptr, int length, T value, U comp)
  169. where T : unmanaged
  170. where U : IComparer<T>
  171. {
  172. var offset = 0;
  173. for (var l = length; l != 0; l >>= 1)
  174. {
  175. var idx = offset + (l >> 1);
  176. var curr = ptr[idx];
  177. var r = comp.Compare(value, curr);
  178. if (r == 0)
  179. {
  180. return idx;
  181. }
  182. if (r > 0)
  183. {
  184. offset = idx + 1;
  185. --l;
  186. }
  187. }
  188. return ~offset;
  189. }
  190. /// <summary>
  191. /// Sorts this array in ascending order.
  192. /// </summary>
  193. /// <typeparam name="T">The type of the elements.</typeparam>
  194. /// <param name="array">The array to sort.</param>
  195. [BurstCompatible(GenericTypeArguments = new[] { typeof(int) })]
  196. public unsafe static void Sort<T>(this NativeArray<T> array)
  197. where T : struct, IComparable<T>
  198. {
  199. IntroSortStruct<T, DefaultComparer<T>>(array.GetUnsafePtr(), array.Length, new DefaultComparer<T>());
  200. }
  201. /// <summary>
  202. /// Sorts this array using a custom comparison.
  203. /// </summary>
  204. /// <typeparam name="T">The type of the elements.</typeparam>
  205. /// <typeparam name="U">The type of the comparer.</typeparam>
  206. /// <param name="array">The array to sort.</param>
  207. /// <param name="comp">The comparison function used to determine the relative order of the elements.</param>
  208. [BurstCompatible(GenericTypeArguments = new[] { typeof(int), typeof(DefaultComparer<int>) })]
  209. public unsafe static void Sort<T, U>(this NativeArray<T> array, U comp)
  210. where T : struct
  211. where U : IComparer<T>
  212. {
  213. IntroSortStruct<T, U>(array.GetUnsafePtr(), array.Length, comp);
  214. }
  215. /// <summary>
  216. /// Sorts this array in ascending order.
  217. /// </summary>
  218. /// <typeparam name="T">Source type of elements</typeparam>
  219. /// <param name="array">The array to sort.</param>
  220. /// <param name="inputDeps">The job handle or handles for any scheduled jobs that use this container.</param>
  221. /// <returns>A new job handle containing the prior handles as well as the handle for the job that sorts
  222. /// the container.</returns>
  223. [NotBurstCompatible /* This is not burst compatible because of IJob's use of a static IntPtr. Should switch to IJobBurstSchedulable in the future */]
  224. [Obsolete("Instead call SortJob(this NativeArray<T>).Schedule(JobHandle). (RemovedAfter 2021-06-20)", false)]
  225. public unsafe static JobHandle Sort<T>(this NativeArray<T> array, JobHandle inputDeps)
  226. where T : unmanaged, IComparable<T>
  227. {
  228. return Sort((T*)NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(array), array.Length, new DefaultComparer<T>(), inputDeps);
  229. }
  230. /// <summary>
  231. /// Returns a job which will sort this array in ascending order.
  232. /// </summary>
  233. /// <remarks>This method does not schedule the job. Scheduling the job is left to you.</remarks>
  234. /// <typeparam name="T">The type of the elements.</typeparam>
  235. /// <param name="array">The array to sort.</param>
  236. /// <returns>A job for sorting this array.</returns>
  237. [BurstCompatible(GenericTypeArguments = new[] { typeof(int) }, RequiredUnityDefine = "UNITY_2020_2_OR_NEWER" /* Due to job scheduling on 2020.1 using statics */)]
  238. public unsafe static SortJob<T, DefaultComparer<T>> SortJob<T>(this NativeArray<T> array)
  239. where T : unmanaged, IComparable<T>
  240. {
  241. return SortJob((T*)NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(array), array.Length, new DefaultComparer<T>());
  242. }
  243. /// <summary>
  244. /// Sorts this array using a custom comparison function.
  245. /// </summary>
  246. /// <typeparam name="T">Source type of elements</typeparam>
  247. /// <typeparam name="U">The comparer type.</typeparam>
  248. /// <param name="array">The array to sort.</param>
  249. /// <param name="comp">A comparison function that determines whether one element in the array is less than, equal to, or greater than another element.</param>
  250. /// <param name="inputDeps">The job handle or handles for any scheduled jobs that use this container.</param>
  251. /// <returns>A new job handle containing the prior handles as well as the handle for the job that sorts
  252. /// the container.</returns>
  253. [NotBurstCompatible /* This is not burst compatible because of IJob's use of a static IntPtr. Should switch to IJobBurstSchedulable in the future */]
  254. [Obsolete("Instead call SortJob(this NativeArray<T>, U).Schedule(JobHandle). (RemovedAfter 2021-06-20)", false)]
  255. public unsafe static JobHandle Sort<T, U>(this NativeArray<T> array, U comp, JobHandle inputDeps)
  256. where T : unmanaged
  257. where U : IComparer<T>
  258. {
  259. return Sort((T*)NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(array), array.Length, comp, inputDeps);
  260. }
  261. /// <summary>
  262. /// Returns a job which will sort this array using a custom comparison.
  263. /// </summary>
  264. /// <remarks>This method does not schedule the job. Scheduling the job is left to you.</remarks>
  265. /// <typeparam name="T">The type of the elements.</typeparam>
  266. /// <typeparam name="U">The type of the comparer.</typeparam>
  267. /// <param name="array">The array to sort.</param>
  268. /// <param name="comp">The comparison function used to determine the relative order of the elements.</param>
  269. /// <returns>A job for sorting the array.</returns>
  270. [BurstCompatible(GenericTypeArguments = new[] { typeof(int), typeof(DefaultComparer<int>) }, RequiredUnityDefine = "UNITY_2020_2_OR_NEWER" /* Due to job scheduling on 2020.1 using statics */)]
  271. public unsafe static SortJob<T, U> SortJob<T, U>(this NativeArray<T> array, U comp)
  272. where T : unmanaged
  273. where U : IComparer<T>
  274. {
  275. return new SortJob<T, U>
  276. {
  277. Data = (T*)NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(array),
  278. Length = array.Length,
  279. Comp = comp
  280. };
  281. }
  282. /// <summary>
  283. /// Finds a value in this sorted array by binary search.
  284. /// </summary>
  285. /// <remarks>If the array is not sorted, the value might not be found, even if it's present in this array.</remarks>
  286. /// <typeparam name="T">The type of the elements.</typeparam>
  287. /// <param name="array">The array to search.</param>
  288. /// <param name="value">The value to locate.</param>
  289. /// <returns>If found, the index of the located value. If not found, the return value is negative.</returns>
  290. [BurstCompatible(GenericTypeArguments = new[] { typeof(int) })]
  291. public static int BinarySearch<T>(this NativeArray<T> array, T value)
  292. where T : unmanaged, IComparable<T>
  293. {
  294. return array.BinarySearch(value, new DefaultComparer<T>());
  295. }
  296. /// <summary>
  297. /// Finds a value in this sorted array by binary search using a custom comparison.
  298. /// </summary>
  299. /// <remarks>If the array is not sorted, the value might not be found, even if it's present in this array.
  300. /// </remarks>
  301. /// <typeparam name="T">The type of the elements.</typeparam>
  302. /// <typeparam name="U">The comparer type.</typeparam>
  303. /// <param name="array">The array to search.</param>
  304. /// <param name="value">The value to locate.</param>
  305. /// <param name="comp">The comparison function used to determine the relative order of the elements.</param>
  306. /// <returns>If found, the index of the located value. If not found, the return value is negative.</returns>
  307. [BurstCompatible(GenericTypeArguments = new[] { typeof(int), typeof(DefaultComparer<int>) })]
  308. public unsafe static int BinarySearch<T, U>(this NativeArray<T> array, T value, U comp)
  309. where T : unmanaged
  310. where U : IComparer<T>
  311. {
  312. return BinarySearch((T*)NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(array), array.Length, value, comp);
  313. }
  314. /// <summary>
  315. /// Sorts this list in ascending order.
  316. /// </summary>
  317. /// <typeparam name="T">The type of the elements.</typeparam>
  318. /// <param name="list">The list to sort.</param>
  319. [BurstCompatible(GenericTypeArguments = new[] { typeof(int) })]
  320. public unsafe static void Sort<T>(this NativeList<T> list)
  321. where T : unmanaged, IComparable<T>
  322. {
  323. list.Sort(new DefaultComparer<T>());
  324. }
  325. /// <summary>
  326. /// Sorts this list using a custom comparison.
  327. /// </summary>
  328. /// <typeparam name="T">The type of the elements.</typeparam>
  329. /// <typeparam name="U">The type of the comparer.</typeparam>
  330. /// <param name="list">The list to sort.</param>
  331. /// <param name="comp">The comparison function used to determine the relative order of the elements.</param>
  332. [BurstCompatible(GenericTypeArguments = new[] { typeof(int), typeof(DefaultComparer<int>) })]
  333. public unsafe static void Sort<T, U>(this NativeList<T> list, U comp)
  334. where T : unmanaged
  335. where U : IComparer<T>
  336. {
  337. IntroSort<T, U>(list.GetUnsafePtr(), list.Length, comp);
  338. }
  339. /// <summary>
  340. /// Sorts this list in ascending order.
  341. /// </summary>
  342. /// <typeparam name="T">Source type of elements</typeparam>
  343. /// <param name="array">The container to perform sort.</param>
  344. /// <param name="inputDeps">The job handle or handles for any scheduled jobs that use this container.</param>
  345. /// <returns>A new job handle containing the prior handles as well as the handle for the job that sorts
  346. /// the container.</returns>
  347. [NotBurstCompatible /* This is not burst compatible because of IJob's use of a static IntPtr. Should switch to IJobBurstSchedulable in the future */]
  348. [Obsolete("Instead call SortJob(this NativeList<T>).Schedule(JobHandle). (RemovedAfter 2021-06-20)", false)]
  349. public unsafe static JobHandle Sort<T>(this NativeList<T> array, JobHandle inputDeps)
  350. where T : unmanaged, IComparable<T>
  351. {
  352. return array.Sort(new DefaultComparer<T>(), inputDeps);
  353. }
  354. /// <summary>
  355. /// Returns a job which will sort this list in ascending order.
  356. /// </summary>
  357. /// <remarks>This method does not schedule the job. Scheduling the job is left to you.</remarks>
  358. /// <typeparam name="T">The type of the elements.</typeparam>
  359. /// <param name="list">The list to sort.</param>
  360. /// <returns>A job for sorting this list.</returns>
  361. [BurstCompatible(GenericTypeArguments = new[] { typeof(int) }, RequiredUnityDefine = "UNITY_2020_2_OR_NEWER" /* Due to job scheduling on 2020.1 using statics */)]
  362. public unsafe static SortJob<T, DefaultComparer<T>> SortJob<T>(this NativeList<T> list)
  363. where T : unmanaged, IComparable<T>
  364. {
  365. return SortJob((T*)list.GetUnsafePtr(), list.Length,new DefaultComparer<T>());
  366. }
  367. /// <summary>
  368. /// Sorts this list using a custom comparison function.
  369. /// </summary>
  370. /// <typeparam name="T">Source type of elements</typeparam>
  371. /// <typeparam name="U">The comparer type.</typeparam>
  372. /// <param name="list">The container to perform sort.</param>
  373. /// <param name="comp">A comparison function that determines whether one element in the array is less than, equal to, or greater than another element.</param>
  374. /// <param name="inputDeps">The job handle or handles for any scheduled jobs that use this container.</param>
  375. /// <returns>A new job handle containing the prior handles as well as the handle for the job that sorts
  376. /// the container.</returns>
  377. [NotBurstCompatible /* This is not burst compatible because of IJob's use of a static IntPtr. Should switch to IJobBurstSchedulable in the future */]
  378. [Obsolete("Instead call SortJob(this NativeList<T>, U).Schedule(JobHandle). (RemovedAfter 2021-06-20)", false)]
  379. public unsafe static JobHandle Sort<T, U>(this NativeList<T> list, U comp, JobHandle inputDeps)
  380. where T : unmanaged
  381. where U : IComparer<T>
  382. {
  383. return Sort((T*)list.GetUnsafePtr(), list.Length, comp, inputDeps);
  384. }
  385. /// <summary>
  386. /// Returns a job which will sort this list using a custom comparison.
  387. /// </summary>
  388. /// <remarks>This method does not schedule the job. Scheduling the job is left to you.</remarks>
  389. /// <typeparam name="T">The type of the elements.</typeparam>
  390. /// <typeparam name="U">The type of the comparer.</typeparam>
  391. /// <param name="list">The list to sort.</param>
  392. /// <param name="comp">The comparison function used to determine the relative order of the elements.</param>
  393. /// <returns>A job for sorting this list.</returns>
  394. [BurstCompatible(GenericTypeArguments = new[] { typeof(int), typeof(DefaultComparer<int>) }, RequiredUnityDefine = "UNITY_2020_2_OR_NEWER" /* Due to job scheduling on 2020.1 using statics */)]
  395. public unsafe static SortJob<T, U> SortJob<T, U>(this NativeList<T> list, U comp)
  396. where T : unmanaged
  397. where U : IComparer<T>
  398. {
  399. return SortJob((T*)list.GetUnsafePtr(), list.Length, comp);
  400. }
  401. /// <summary>
  402. /// Finds a value in this sorted list by binary search.
  403. /// </summary>
  404. /// <remarks>If this list is not sorted, the value might not be found, even if it's present in this list.</remarks>
  405. /// <typeparam name="T">The type of the elements.</typeparam>
  406. /// <param name="list">The list to search.</param>
  407. /// <param name="value">The value to locate.</param>
  408. /// <returns>If found, the index of the located value. If not found, the return value is negative.</returns>
  409. [BurstCompatible(GenericTypeArguments = new[] { typeof(int) })]
  410. public static int BinarySearch<T>(this NativeList<T> list, T value)
  411. where T : unmanaged, IComparable<T>
  412. {
  413. return list.BinarySearch(value, new DefaultComparer<T>());
  414. }
  415. /// <summary>
  416. /// Finds a value in this sorted list by binary search using a custom comparison.
  417. /// </summary>
  418. /// <remarks>If this list is not sorted, the value may not be found, even if it's present in this list.</remarks>
  419. /// <typeparam name="T">The type of the elements.</typeparam>
  420. /// <typeparam name="U">The type of the comparer.</typeparam>
  421. /// <param name="list">The list to search.</param>
  422. /// <param name="value">The value to locate.</param>
  423. /// <param name="comp">The comparison function used to determine the relative order of the elements.</param>
  424. /// <returns>If found, the index of the located value. If not found, the return value is negative.</returns>
  425. [BurstCompatible(GenericTypeArguments = new[] { typeof(int), typeof(DefaultComparer<int>) })]
  426. public unsafe static int BinarySearch<T, U>(this NativeList<T> list, T value, U comp)
  427. where T : unmanaged
  428. where U : IComparer<T>
  429. {
  430. return BinarySearch((T*)list.GetUnsafePtr(), list.Length, value, comp);
  431. }
  432. /// <summary>
  433. /// Sorts this list in ascending order.
  434. /// </summary>
  435. /// <typeparam name="T">The type of the elements.</typeparam>
  436. /// <param name="list">The list to sort.</param>
  437. [BurstCompatible(GenericTypeArguments = new[] { typeof(int) })]
  438. public unsafe static void Sort<T>(this UnsafeList<T> list) where T : unmanaged, IComparable<T>
  439. {
  440. list.Sort(new DefaultComparer<T>());
  441. }
  442. /// <summary>
  443. /// Sorts the list using a custom comparison.
  444. /// </summary>
  445. /// <typeparam name="T">The type of the elements.</typeparam>
  446. /// <typeparam name="U">The type of the comparer.</typeparam>
  447. /// <param name="list">The list to sort.</param>
  448. /// <param name="comp">The comparison function used to determine the relative order of the elements.</param>
  449. [BurstCompatible(GenericTypeArguments = new[] { typeof(int), typeof(DefaultComparer<int>) })]
  450. public unsafe static void Sort<T, U>(this UnsafeList<T> list, U comp)
  451. where T : unmanaged
  452. where U : IComparer<T>
  453. {
  454. IntroSort<T, U>(list.Ptr, list.Length, comp);
  455. }
  456. /// <summary>
  457. /// Sorts this list in ascending order.
  458. /// </summary>
  459. /// <typeparam name="T">Source type of elements</typeparam>
  460. /// <param name="list">The container to perform sort.</param>
  461. /// <param name="inputDeps">The job handle or handles for any scheduled jobs that use this container.</param>
  462. /// <returns>A new job handle containing the prior handles as well as the handle for the job that sorts
  463. /// the container.</returns>
  464. [NotBurstCompatible /* This is not burst compatible because of IJob's use of a static IntPtr. Should switch to IJobBurstSchedulable in the future */]
  465. [Obsolete("Instead call SortJob(this UnsafeList<T>).Schedule(JobHandle). (RemovedAfter 2021-06-20)", false)]
  466. public unsafe static JobHandle Sort<T>(this UnsafeList<T> list, JobHandle inputDeps)
  467. where T : unmanaged, IComparable<T>
  468. {
  469. return list.Sort(new DefaultComparer<T>(), inputDeps);
  470. }
  471. /// <summary>
  472. /// Returns a job which will sort this list in ascending order.
  473. /// </summary>
  474. /// <remarks>This method does not schedule the job. Scheduling the job is left to you.</remarks>
  475. /// <typeparam name="T">The type of the elements.</typeparam>
  476. /// <param name="list">The list to sort.</param>
  477. /// <returns>A job for sorting this list.</returns>
  478. [BurstCompatible(GenericTypeArguments = new[] { typeof(int) }, RequiredUnityDefine = "UNITY_2020_2_OR_NEWER" /* Due to job scheduling on 2020.1 using statics */)]
  479. public unsafe static SortJob<T, DefaultComparer<T>> SortJob<T>(this UnsafeList<T> list)
  480. where T : unmanaged, IComparable<T>
  481. {
  482. return SortJob((T*)list.Ptr, list.Length, new DefaultComparer<T>());
  483. }
  484. /// <summary>
  485. /// Sorts this list using a custom comparison function.
  486. /// </summary>
  487. /// <typeparam name="T">Source type of elements</typeparam>
  488. /// <typeparam name="U">The comparer type.</typeparam>
  489. /// <param name="list">The container to perform sort.</param>
  490. /// <param name="comp">A comparison function that determines whether one element in the array is less than, equal to, or greater than another element.</param>
  491. /// <param name="inputDeps">The job handle or handles for any scheduled jobs that use this container.</param>
  492. /// <returns>A new job handle containing the prior handles as well as the handle for the job that sorts
  493. /// the container.</returns>
  494. [NotBurstCompatible /* This is not burst compatible because of IJob's use of a static IntPtr. Should switch to IJobBurstSchedulable in the future */]
  495. [Obsolete("Instead call SortJob(this UnsafeList<T>, U).Schedule(JobHandle). (RemovedAfter 2021-06-20)", false)]
  496. public unsafe static JobHandle Sort<T, U>(this UnsafeList<T> list, U comp, JobHandle inputDeps)
  497. where T : unmanaged
  498. where U : IComparer<T>
  499. {
  500. return Sort(list.Ptr, list.Length, comp, inputDeps);
  501. }
  502. /// <summary>
  503. /// Returns a job which will sort this list using a custom comparison.
  504. /// </summary>
  505. /// <remarks>This method does not schedule the job. Scheduling the job is left to you.</remarks>
  506. /// <typeparam name="T">The type of the elements.</typeparam>
  507. /// <typeparam name="U">The type of the comparer.</typeparam>
  508. /// <param name="list">The list to sort.</param>
  509. /// <param name="comp">The comparison function used to determine the relative order of the elements.</param>
  510. /// <returns>A job for sorting this list.</returns>
  511. [BurstCompatible(GenericTypeArguments = new[] { typeof(int), typeof(DefaultComparer<int>) }, RequiredUnityDefine = "UNITY_2020_2_OR_NEWER" /* Due to job scheduling on 2020.1 using statics */)]
  512. public unsafe static SortJob<T, U> SortJob<T, U>(this UnsafeList<T> list, U comp)
  513. where T : unmanaged
  514. where U : IComparer<T>
  515. {
  516. return SortJob(list.Ptr, list.Length, comp);
  517. }
  518. /// <summary>
  519. /// Finds a value in this sorted list by binary search.
  520. /// </summary>
  521. /// <remarks>If this list is not sorted, the value might not be found, even if it's present in this list.</remarks>
  522. /// <typeparam name="T">The type of the elements.</typeparam>
  523. /// <param name="list">The list to search.</param>
  524. /// <param name="value">The value to locate.</param>
  525. /// <returns>If found, the index of the located value. If not found, the return value is negative.</returns>
  526. [BurstCompatible(GenericTypeArguments = new[] { typeof(int) })]
  527. public static int BinarySearch<T>(this UnsafeList<T> list, T value)
  528. where T : unmanaged, IComparable<T>
  529. {
  530. return list.BinarySearch(value, new DefaultComparer<T>());
  531. }
  532. /// <summary>
  533. /// Finds a value in this sorted list by binary search using a custom comparison.
  534. /// </summary>
  535. /// <remarks>If this list is not sorted, the value might not be found, even if it's present in this list.</remarks>
  536. /// <typeparam name="T">The type of the elements.</typeparam>
  537. /// <typeparam name="U">The type of the comparer.</typeparam>
  538. /// <param name="list">The list to search.</param>
  539. /// <param name="value">The value to locate.</param>
  540. /// <param name="comp">The comparison function used to determine the relative order of the elements.</param>
  541. /// <returns>If found, the index of the located value. If not found, the return value is negative.</returns>
  542. [BurstCompatible(GenericTypeArguments = new[] { typeof(int), typeof(DefaultComparer<int>) })]
  543. public unsafe static int BinarySearch<T, U>(this UnsafeList<T> list, T value, U comp)
  544. where T : unmanaged
  545. where U : IComparer<T>
  546. {
  547. return BinarySearch(list.Ptr, list.Length, value, comp);
  548. }
  549. /// <summary>
  550. /// Sorts this slice in ascending order.
  551. /// </summary>
  552. /// <typeparam name="T">The type of the elements.</typeparam>
  553. /// <param name="slice">The slice to sort.</param>
  554. [BurstCompatible(GenericTypeArguments = new[] { typeof(int) })]
  555. public unsafe static void Sort<T>(this NativeSlice<T> slice)
  556. where T : struct, IComparable<T>
  557. {
  558. slice.Sort(new DefaultComparer<T>());
  559. }
  560. /// <summary>
  561. /// Sorts this slice using a custom comparison.
  562. /// </summary>
  563. /// <typeparam name="T">The type of the elements.</typeparam>
  564. /// <typeparam name="U">The type of the comparer.</typeparam>
  565. /// <param name="slice">The slice to sort.</param>
  566. /// <param name="comp">The comparison function used to determine the relative order of the elements.</param>
  567. [BurstCompatible(GenericTypeArguments = new[] { typeof(int), typeof(DefaultComparer<int>) })]
  568. public unsafe static void Sort<T, U>(this NativeSlice<T> slice, U comp)
  569. where T : struct
  570. where U : IComparer<T>
  571. {
  572. CheckStrideMatchesSize<T>(slice.Stride);
  573. IntroSortStruct<T, U>(slice.GetUnsafePtr(), slice.Length, comp);
  574. }
  575. /// <summary>
  576. /// Sorts this slice in ascending order.
  577. /// </summary>
  578. /// <typeparam name="T">Source type of elements</typeparam>
  579. /// <param name="slice">The container to perform sort.</param>
  580. /// <param name="inputDeps">The job handle or handles for any scheduled jobs that use this container.</param>
  581. /// <returns>A new job handle containing the prior handles as well as the handle for the job that sorts
  582. /// the container.</returns>
  583. [NotBurstCompatible /* This is not burst compatible because of IJob's use of a static IntPtr. Should switch to IJobBurstSchedulable in the future */]
  584. [Obsolete("Instead call SortJob(this NativeSlice<T>).Schedule(JobHandle). (RemovedAfter 2021-06-20)", false)]
  585. public unsafe static JobHandle Sort<T>(this NativeSlice<T> slice, JobHandle inputDeps)
  586. where T : unmanaged, IComparable<T>
  587. {
  588. return slice.Sort(new DefaultComparer<T>(), inputDeps);
  589. }
  590. /// <summary>
  591. /// Returns a job which will sort this slice in ascending order.
  592. /// </summary>
  593. /// <remarks>This method does not schedule the job. Scheduling the job is left to you.</remarks>
  594. /// <typeparam name="T">The type of the elements.</typeparam>
  595. /// <param name="slice">The slice to sort.</param>
  596. /// <returns>A job for sorting this slice.</returns>
  597. [BurstCompatible(GenericTypeArguments = new[] { typeof(int) }, RequiredUnityDefine = "UNITY_2020_2_OR_NEWER" /* Due to job scheduling on 2020.1 using statics */)]
  598. public unsafe static SortJob<T, DefaultComparer<T>> SortJob<T>(this NativeSlice<T> slice)
  599. where T : unmanaged, IComparable<T>
  600. {
  601. CheckStrideMatchesSize<T>(slice.Stride);
  602. return SortJob((T*)slice.GetUnsafePtr(), slice.Length, new DefaultComparer<T>());
  603. }
  604. /// <summary>
  605. /// Sorts this slice using a custom comparison function.
  606. /// </summary>
  607. /// <typeparam name="T">Source type of elements</typeparam>
  608. /// <typeparam name="U">The comparer type.</typeparam>
  609. /// <param name="slice">The container to perform sort.</param>
  610. /// <param name="comp">A comparison function that determines whether one element in the array is less than, equal to, or greater than another element.</param>
  611. /// <param name="inputDeps">The job handle or handles for any scheduled jobs that use this container.</param>
  612. /// <returns>A new job handle containing the prior handles as well as the handle for the job that sorts
  613. /// the container.</returns>
  614. [NotBurstCompatible /* This is not burst compatible because of IJob's use of a static IntPtr. Should switch to IJobBurstSchedulable in the future */]
  615. [Obsolete("Instead call SortJob(this NativeSlice<T>, U).Schedule(JobHandle). (RemovedAfter 2021-06-20)", false)]
  616. public unsafe static JobHandle Sort<T, U>(this NativeSlice<T> slice, U comp, JobHandle inputDeps)
  617. where T : unmanaged
  618. where U : IComparer<T>
  619. {
  620. return Sort((T*)slice.GetUnsafePtr(), slice.Length, comp, inputDeps);
  621. }
  622. /// <summary>
  623. /// Returns a job which will sort this slice using a custom comparison.
  624. /// </summary>
  625. /// <remarks>This method does not schedule the job. Scheduling the job is left to you.</remarks>
  626. /// <typeparam name="T">The type of the elements.</typeparam>
  627. /// <typeparam name="U">The type of the comparer.</typeparam>
  628. /// <param name="slice">The slice to sort.</param>
  629. /// <param name="comp">The comparison function used to determine the relative order of the elements.</param>
  630. /// <returns>A job for sorting this slice.</returns>
  631. [BurstCompatible(GenericTypeArguments = new[] { typeof(int), typeof(DefaultComparer<int>) }, RequiredUnityDefine = "UNITY_2020_2_OR_NEWER" /* Due to job scheduling on 2020.1 using statics */)]
  632. public unsafe static SortJob<T, U> SortJob<T, U>(this NativeSlice<T> slice, U comp)
  633. where T : unmanaged
  634. where U : IComparer<T>
  635. {
  636. CheckStrideMatchesSize<T>(slice.Stride);
  637. return SortJob((T*)slice.GetUnsafePtr(), slice.Length, comp);
  638. }
  639. /// <summary>
  640. /// Finds a value in this sorted slice by binary search.
  641. /// </summary>
  642. /// <remarks>If this slice is not sorted, the value might not be found, even if it's present in this slice.</remarks>
  643. /// <typeparam name="T">The type of the elements.</typeparam>
  644. /// <param name="slice">The slice to search.</param>
  645. /// <param name="value">The value to locate.</param>
  646. /// <returns>If found, the index of the located value. If not found, the return value is negative.</returns>
  647. [BurstCompatible(GenericTypeArguments = new[] { typeof(int) })]
  648. public static int BinarySearch<T>(this NativeSlice<T> slice, T value)
  649. where T : unmanaged, IComparable<T>
  650. {
  651. return slice.BinarySearch(value, new DefaultComparer<T>());
  652. }
  653. /// <summary>
  654. /// Finds a value in this sorted slice by binary search using a custom comparison.
  655. /// </summary>
  656. /// <remarks>If this slice is not sorted, the value might not be found, even if it's present in this slice.</remarks>
  657. /// <typeparam name="T">The type of the elements.</typeparam>
  658. /// <typeparam name="U">The type of the comparer.</typeparam>
  659. /// <param name="slice">The slice to search.</param>
  660. /// <param name="value">The value to locate.</param>
  661. /// <param name="comp">The comparison function used to determine the relative order of the elements.</param>
  662. /// <returns>If found, the index of the located value. If not found, the return value is negative.</returns>
  663. [BurstCompatible(GenericTypeArguments = new[] { typeof(int), typeof(DefaultComparer<int>) })]
  664. public unsafe static int BinarySearch<T, U>(this NativeSlice<T> slice, T value, U comp)
  665. where T : unmanaged
  666. where U : IComparer<T>
  667. {
  668. return BinarySearch((T*)slice.GetUnsafePtr(), slice.Length, value, comp);
  669. }
  670. /// -- Internals
  671. [BurstCompatible(GenericTypeArguments = new[] { typeof(int), typeof(DefaultComparer<int>) })]
  672. unsafe internal static void IntroSort<T, U>(void* array, int length, U comp)
  673. where T : unmanaged
  674. where U : IComparer<T>
  675. {
  676. IntroSort<T, U>(array, 0, length - 1, 2 * CollectionHelper.Log2Floor(length), comp);
  677. }
  678. const int k_IntrosortSizeThreshold = 16;
  679. unsafe static void IntroSort<T, U>(void* array, int lo, int hi, int depth, U comp)
  680. where T : unmanaged
  681. where U : IComparer<T>
  682. {
  683. while (hi > lo)
  684. {
  685. int partitionSize = hi - lo + 1;
  686. if (partitionSize <= k_IntrosortSizeThreshold)
  687. {
  688. if (partitionSize == 1)
  689. {
  690. return;
  691. }
  692. if (partitionSize == 2)
  693. {
  694. SwapIfGreaterWithItems<T, U>(array, lo, hi, comp);
  695. return;
  696. }
  697. if (partitionSize == 3)
  698. {
  699. SwapIfGreaterWithItems<T, U>(array, lo, hi - 1, comp);
  700. SwapIfGreaterWithItems<T, U>(array, lo, hi, comp);
  701. SwapIfGreaterWithItems<T, U>(array, hi - 1, hi, comp);
  702. return;
  703. }
  704. InsertionSort<T, U>(array, lo, hi, comp);
  705. return;
  706. }
  707. if (depth == 0)
  708. {
  709. HeapSort<T, U>(array, lo, hi, comp);
  710. return;
  711. }
  712. depth--;
  713. int p = Partition<T, U>(array, lo, hi, comp);
  714. IntroSort<T, U>(array, p + 1, hi, depth, comp);
  715. hi = p - 1;
  716. }
  717. }
  718. unsafe static void InsertionSort<T, U>(void* array, int lo, int hi, U comp)
  719. where T : unmanaged
  720. where U : IComparer<T>
  721. {
  722. int i, j;
  723. T t;
  724. for (i = lo; i < hi; i++)
  725. {
  726. j = i;
  727. t = UnsafeUtility.ReadArrayElement<T>(array, i + 1);
  728. while (j >= lo && comp.Compare(t, UnsafeUtility.ReadArrayElement<T>(array, j)) < 0)
  729. {
  730. UnsafeUtility.WriteArrayElement<T>(array, j + 1, UnsafeUtility.ReadArrayElement<T>(array, j));
  731. j--;
  732. }
  733. UnsafeUtility.WriteArrayElement<T>(array, j + 1, t);
  734. }
  735. }
  736. unsafe static int Partition<T, U>(void* array, int lo, int hi, U comp)
  737. where T : unmanaged
  738. where U : IComparer<T>
  739. {
  740. int mid = lo + ((hi - lo) / 2);
  741. SwapIfGreaterWithItems<T, U>(array, lo, mid, comp);
  742. SwapIfGreaterWithItems<T, U>(array, lo, hi, comp);
  743. SwapIfGreaterWithItems<T, U>(array, mid, hi, comp);
  744. T pivot = UnsafeUtility.ReadArrayElement<T>(array, mid);
  745. Swap<T>(array, mid, hi - 1);
  746. int left = lo, right = hi - 1;
  747. while (left < right)
  748. {
  749. while (comp.Compare(pivot, UnsafeUtility.ReadArrayElement<T>(array, ++left)) > 0) ;
  750. while (comp.Compare(pivot, UnsafeUtility.ReadArrayElement<T>(array, --right)) < 0) ;
  751. if (left >= right)
  752. break;
  753. Swap<T>(array, left, right);
  754. }
  755. Swap<T>(array, left, (hi - 1));
  756. return left;
  757. }
  758. unsafe static void HeapSort<T, U>(void* array, int lo, int hi, U comp)
  759. where T : unmanaged
  760. where U : IComparer<T>
  761. {
  762. int n = hi - lo + 1;
  763. for (int i = n / 2; i >= 1; i--)
  764. {
  765. Heapify<T, U>(array, i, n, lo, comp);
  766. }
  767. for (int i = n; i > 1; i--)
  768. {
  769. Swap<T>(array, lo, lo + i - 1);
  770. Heapify<T, U>(array, 1, i - 1, lo, comp);
  771. }
  772. }
  773. unsafe static void Heapify<T, U>(void* array, int i, int n, int lo, U comp)
  774. where T : unmanaged
  775. where U : IComparer<T>
  776. {
  777. T val = UnsafeUtility.ReadArrayElement<T>(array, lo + i - 1);
  778. int child;
  779. while (i <= n / 2)
  780. {
  781. child = 2 * i;
  782. if (child < n && (comp.Compare(UnsafeUtility.ReadArrayElement<T>(array, lo + child - 1), UnsafeUtility.ReadArrayElement<T>(array, (lo + child))) < 0))
  783. {
  784. child++;
  785. }
  786. if (comp.Compare(UnsafeUtility.ReadArrayElement<T>(array, (lo + child - 1)), val) < 0)
  787. break;
  788. UnsafeUtility.WriteArrayElement(array, lo + i - 1, UnsafeUtility.ReadArrayElement<T>(array, lo + child - 1));
  789. i = child;
  790. }
  791. UnsafeUtility.WriteArrayElement(array, lo + i - 1, val);
  792. }
  793. unsafe static void Swap<T>(void* array, int lhs, int rhs) where T : unmanaged
  794. {
  795. T val = UnsafeUtility.ReadArrayElement<T>(array, lhs);
  796. UnsafeUtility.WriteArrayElement(array, lhs, UnsafeUtility.ReadArrayElement<T>(array, rhs));
  797. UnsafeUtility.WriteArrayElement(array, rhs, val);
  798. }
  799. unsafe static void SwapIfGreaterWithItems<T, U>(void* array, int lhs, int rhs, U comp)
  800. where T : unmanaged
  801. where U : IComparer<T>
  802. {
  803. if (lhs != rhs)
  804. {
  805. if (comp.Compare(UnsafeUtility.ReadArrayElement<T>(array, lhs), UnsafeUtility.ReadArrayElement<T>(array, rhs)) > 0)
  806. {
  807. Swap<T>(array, lhs, rhs);
  808. }
  809. }
  810. }
  811. unsafe static void IntroSortStruct<T, U>(void* array, int length, U comp)
  812. where T : struct
  813. where U : IComparer<T>
  814. {
  815. IntroSortStruct<T, U>(array, 0, length - 1, 2 * CollectionHelper.Log2Floor(length), comp);
  816. }
  817. unsafe static void IntroSortStruct<T, U>(void* array, int lo, int hi, int depth, U comp)
  818. where T : struct
  819. where U : IComparer<T>
  820. {
  821. while (hi > lo)
  822. {
  823. int partitionSize = hi - lo + 1;
  824. if (partitionSize <= k_IntrosortSizeThreshold)
  825. {
  826. if (partitionSize == 1)
  827. {
  828. return;
  829. }
  830. if (partitionSize == 2)
  831. {
  832. SwapIfGreaterWithItemsStruct<T, U>(array, lo, hi, comp);
  833. return;
  834. }
  835. if (partitionSize == 3)
  836. {
  837. SwapIfGreaterWithItemsStruct<T, U>(array, lo, hi - 1, comp);
  838. SwapIfGreaterWithItemsStruct<T, U>(array, lo, hi, comp);
  839. SwapIfGreaterWithItemsStruct<T, U>(array, hi - 1, hi, comp);
  840. return;
  841. }
  842. InsertionSortStruct<T, U>(array, lo, hi, comp);
  843. return;
  844. }
  845. if (depth == 0)
  846. {
  847. HeapSortStruct<T, U>(array, lo, hi, comp);
  848. return;
  849. }
  850. depth--;
  851. int p = PartitionStruct<T, U>(array, lo, hi, comp);
  852. IntroSortStruct<T, U>(array, p + 1, hi, depth, comp);
  853. hi = p - 1;
  854. }
  855. }
  856. unsafe static void InsertionSortStruct<T, U>(void* array, int lo, int hi, U comp)
  857. where T : struct
  858. where U : IComparer<T>
  859. {
  860. int i, j;
  861. T t;
  862. for (i = lo; i < hi; i++)
  863. {
  864. j = i;
  865. t = UnsafeUtility.ReadArrayElement<T>(array, i + 1);
  866. while (j >= lo && comp.Compare(t, UnsafeUtility.ReadArrayElement<T>(array, j)) < 0)
  867. {
  868. UnsafeUtility.WriteArrayElement<T>(array, j + 1, UnsafeUtility.ReadArrayElement<T>(array, j));
  869. j--;
  870. }
  871. UnsafeUtility.WriteArrayElement<T>(array, j + 1, t);
  872. }
  873. }
  874. unsafe static int PartitionStruct<T, U>(void* array, int lo, int hi, U comp)
  875. where T : struct
  876. where U : IComparer<T>
  877. {
  878. int mid = lo + ((hi - lo) / 2);
  879. SwapIfGreaterWithItemsStruct<T, U>(array, lo, mid, comp);
  880. SwapIfGreaterWithItemsStruct<T, U>(array, lo, hi, comp);
  881. SwapIfGreaterWithItemsStruct<T, U>(array, mid, hi, comp);
  882. T pivot = UnsafeUtility.ReadArrayElement<T>(array, mid);
  883. SwapStruct<T>(array, mid, hi - 1);
  884. int left = lo, right = hi - 1;
  885. while (left < right)
  886. {
  887. while (comp.Compare(pivot, UnsafeUtility.ReadArrayElement<T>(array, ++left)) > 0) ;
  888. while (comp.Compare(pivot, UnsafeUtility.ReadArrayElement<T>(array, --right)) < 0) ;
  889. if (left >= right)
  890. break;
  891. SwapStruct<T>(array, left, right);
  892. }
  893. SwapStruct<T>(array, left, (hi - 1));
  894. return left;
  895. }
  896. unsafe static void HeapSortStruct<T, U>(void* array, int lo, int hi, U comp)
  897. where T : struct
  898. where U : IComparer<T>
  899. {
  900. int n = hi - lo + 1;
  901. for (int i = n / 2; i >= 1; i--)
  902. {
  903. HeapifyStruct<T, U>(array, i, n, lo, comp);
  904. }
  905. for (int i = n; i > 1; i--)
  906. {
  907. SwapStruct<T>(array, lo, lo + i - 1);
  908. HeapifyStruct<T, U>(array, 1, i - 1, lo, comp);
  909. }
  910. }
  911. unsafe static void HeapifyStruct<T, U>(void* array, int i, int n, int lo, U comp)
  912. where T : struct
  913. where U : IComparer<T>
  914. {
  915. T val = UnsafeUtility.ReadArrayElement<T>(array, lo + i - 1);
  916. int child;
  917. while (i <= n / 2)
  918. {
  919. child = 2 * i;
  920. if (child < n && (comp.Compare(UnsafeUtility.ReadArrayElement<T>(array, lo + child - 1), UnsafeUtility.ReadArrayElement<T>(array, (lo + child))) < 0))
  921. {
  922. child++;
  923. }
  924. if (comp.Compare(UnsafeUtility.ReadArrayElement<T>(array, (lo + child - 1)), val) < 0)
  925. break;
  926. UnsafeUtility.WriteArrayElement(array, lo + i - 1, UnsafeUtility.ReadArrayElement<T>(array, lo + child - 1));
  927. i = child;
  928. }
  929. UnsafeUtility.WriteArrayElement(array, lo + i - 1, val);
  930. }
  931. unsafe static void SwapStruct<T>(void* array, int lhs, int rhs)
  932. where T : struct
  933. {
  934. T val = UnsafeUtility.ReadArrayElement<T>(array, lhs);
  935. UnsafeUtility.WriteArrayElement(array, lhs, UnsafeUtility.ReadArrayElement<T>(array, rhs));
  936. UnsafeUtility.WriteArrayElement(array, rhs, val);
  937. }
  938. unsafe static void SwapIfGreaterWithItemsStruct<T, U>(void* array, int lhs, int rhs, U comp)
  939. where T : struct
  940. where U : IComparer<T>
  941. {
  942. if (lhs != rhs)
  943. {
  944. if (comp.Compare(UnsafeUtility.ReadArrayElement<T>(array, lhs), UnsafeUtility.ReadArrayElement<T>(array, rhs)) > 0)
  945. {
  946. SwapStruct<T>(array, lhs, rhs);
  947. }
  948. }
  949. }
  950. [BurstCompile]
  951. unsafe struct SegmentSort<T, U> : IJobParallelFor
  952. where T : unmanaged
  953. where U : IComparer<T>
  954. {
  955. [NativeDisableUnsafePtrRestriction]
  956. public T* Data;
  957. public U Comp;
  958. public int Length;
  959. public int SegmentWidth;
  960. public void Execute(int index)
  961. {
  962. var startIndex = index * SegmentWidth;
  963. var segmentLength = ((Length - startIndex) < SegmentWidth) ? (Length - startIndex) : SegmentWidth;
  964. Sort(Data + startIndex, segmentLength, Comp);
  965. }
  966. }
  967. [BurstCompile]
  968. unsafe struct SegmentSortMerge<T, U> : IJob
  969. where T : unmanaged
  970. where U : IComparer<T>
  971. {
  972. [NativeDisableUnsafePtrRestriction]
  973. public T* Data;
  974. public U Comp;
  975. public int Length;
  976. public int SegmentWidth;
  977. public void Execute()
  978. {
  979. var segmentCount = (Length + (SegmentWidth - 1)) / SegmentWidth;
  980. var segmentIndex = stackalloc int[segmentCount];
  981. var resultCopy = (T*)Memory.Unmanaged.Allocate(UnsafeUtility.SizeOf<T>() * Length, 16, Allocator.Temp);
  982. for (int sortIndex = 0; sortIndex < Length; sortIndex++)
  983. {
  984. // find next best
  985. int bestSegmentIndex = -1;
  986. T bestValue = default(T);
  987. for (int i = 0; i < segmentCount; i++)
  988. {
  989. var startIndex = i * SegmentWidth;
  990. var offset = segmentIndex[i];
  991. var segmentLength = ((Length - startIndex) < SegmentWidth) ? (Length - startIndex) : SegmentWidth;
  992. if (offset == segmentLength)
  993. continue;
  994. var nextValue = Data[startIndex + offset];
  995. if (bestSegmentIndex != -1)
  996. {
  997. if (Comp.Compare(nextValue, bestValue) > 0)
  998. continue;
  999. }
  1000. bestValue = nextValue;
  1001. bestSegmentIndex = i;
  1002. }
  1003. segmentIndex[bestSegmentIndex]++;
  1004. resultCopy[sortIndex] = bestValue;
  1005. }
  1006. UnsafeUtility.MemCpy(Data, resultCopy, UnsafeUtility.SizeOf<T>() * Length);
  1007. }
  1008. }
  1009. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
  1010. static void CheckStrideMatchesSize<T>(int stride) where T : struct
  1011. {
  1012. if (stride != UnsafeUtility.SizeOf<T>())
  1013. {
  1014. throw new InvalidOperationException("Sort requires that stride matches the size of the source type");
  1015. }
  1016. }
  1017. }
  1018. /// <summary>
  1019. /// Returned by the `SortJob` methods of <see cref="Unity.Collections.NativeSortExtension"/>. Call `Schedule` to schedule the sorting.
  1020. /// </summary>
  1021. /// <typeparam name="T">The type of the elements to sort.</typeparam>
  1022. /// <typeparam name="U">The type of the comparer.</typeparam>
  1023. [BurstCompatible(GenericTypeArguments = new[] { typeof(int), typeof(NativeSortExtension.DefaultComparer<int>) }, RequiredUnityDefine = "UNITY_2020_2_OR_NEWER" /* Due to job scheduling on 2020.1 using statics */)]
  1024. public unsafe struct SortJob<T, U>
  1025. where T : unmanaged
  1026. where U : IComparer<T>
  1027. {
  1028. /// <summary>
  1029. /// The data to sort.
  1030. /// </summary>
  1031. public T* Data;
  1032. /// <summary>
  1033. /// Comparison function.
  1034. /// </summary>
  1035. public U Comp;
  1036. /// <summary>
  1037. /// The length to sort.
  1038. /// </summary>
  1039. public int Length;
  1040. [BurstCompile]
  1041. struct SegmentSort : IJobParallelFor
  1042. {
  1043. [NativeDisableUnsafePtrRestriction]
  1044. public T* Data;
  1045. public U Comp;
  1046. public int Length;
  1047. public int SegmentWidth;
  1048. public void Execute(int index)
  1049. {
  1050. var startIndex = index * SegmentWidth;
  1051. var segmentLength = ((Length - startIndex) < SegmentWidth) ? (Length - startIndex) : SegmentWidth;
  1052. NativeSortExtension.Sort(Data + startIndex, segmentLength, Comp);
  1053. }
  1054. }
  1055. [BurstCompile]
  1056. struct SegmentSortMerge : IJob
  1057. {
  1058. [NativeDisableUnsafePtrRestriction]
  1059. public T* Data;
  1060. public U Comp;
  1061. public int Length;
  1062. public int SegmentWidth;
  1063. public void Execute()
  1064. {
  1065. var segmentCount = (Length + (SegmentWidth - 1)) / SegmentWidth;
  1066. var segmentIndex = stackalloc int[segmentCount];
  1067. var resultCopy = (T*)Memory.Unmanaged.Allocate(UnsafeUtility.SizeOf<T>() * Length, 16, Allocator.Temp);
  1068. for (int sortIndex = 0; sortIndex < Length; sortIndex++)
  1069. {
  1070. // find next best
  1071. int bestSegmentIndex = -1;
  1072. T bestValue = default(T);
  1073. for (int i = 0; i < segmentCount; i++)
  1074. {
  1075. var startIndex = i * SegmentWidth;
  1076. var offset = segmentIndex[i];
  1077. var segmentLength = ((Length - startIndex) < SegmentWidth) ? (Length - startIndex) : SegmentWidth;
  1078. if (offset == segmentLength)
  1079. continue;
  1080. var nextValue = Data[startIndex + offset];
  1081. if (bestSegmentIndex != -1)
  1082. {
  1083. if (Comp.Compare(nextValue, bestValue) > 0)
  1084. continue;
  1085. }
  1086. bestValue = nextValue;
  1087. bestSegmentIndex = i;
  1088. }
  1089. segmentIndex[bestSegmentIndex]++;
  1090. resultCopy[sortIndex] = bestValue;
  1091. }
  1092. UnsafeUtility.MemCpy(Data, resultCopy, UnsafeUtility.SizeOf<T>() * Length);
  1093. }
  1094. }
  1095. /// <summary>
  1096. /// Schedules this job.
  1097. /// </summary>
  1098. /// <param name="inputDeps">Handle of a job to depend upon.</param>
  1099. /// <returns>The handle of this newly scheduled job.</returns>
  1100. [NotBurstCompatible /* This is not burst compatible because of IJob's use of a static IntPtr. Should switch to IJobBurstSchedulable in the future */]
  1101. public JobHandle Schedule(JobHandle inputDeps = default)
  1102. {
  1103. if (Length == 0)
  1104. return inputDeps;
  1105. var segmentCount = (Length + 1023) / 1024;
  1106. var workerCount = math.max(1, JobsUtility.MaxJobThreadCount);
  1107. var workerSegmentCount = segmentCount / workerCount;
  1108. var segmentSortJob = new SegmentSort { Data = Data, Comp = Comp, Length = Length, SegmentWidth = 1024 };
  1109. var segmentSortJobHandle = segmentSortJob.Schedule(segmentCount, workerSegmentCount, inputDeps);
  1110. var segmentSortMergeJob = new SegmentSortMerge { Data = Data, Comp = Comp, Length = Length, SegmentWidth = 1024 };
  1111. var segmentSortMergeJobHandle = segmentSortMergeJob.Schedule(segmentSortJobHandle);
  1112. return segmentSortMergeJobHandle;
  1113. }
  1114. }
  1115. }