2
0

ObjectPool.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. #if UNITY_5_3_OR_NEWER
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Threading;
  6. namespace UniRx.Toolkit
  7. {
  8. /// <summary>
  9. /// Bass class of ObjectPool.
  10. /// </summary>
  11. public abstract class ObjectPool<T> : IDisposable
  12. where T : UnityEngine.Component
  13. {
  14. bool isDisposed = false;
  15. Queue<T> q;
  16. /// <summary>
  17. /// Limit of instace count.
  18. /// </summary>
  19. protected int MaxPoolCount
  20. {
  21. get
  22. {
  23. return int.MaxValue;
  24. }
  25. }
  26. /// <summary>
  27. /// Create instance when needed.
  28. /// </summary>
  29. protected abstract T CreateInstance();
  30. /// <summary>
  31. /// Called before return to pool, useful for set active object(it is default behavior).
  32. /// </summary>
  33. protected virtual void OnBeforeRent(T instance)
  34. {
  35. instance.gameObject.SetActive(true);
  36. }
  37. /// <summary>
  38. /// Called before return to pool, useful for set inactive object(it is default behavior).
  39. /// </summary>
  40. protected virtual void OnBeforeReturn(T instance)
  41. {
  42. instance.gameObject.SetActive(false);
  43. }
  44. /// <summary>
  45. /// Called when clear or disposed, useful for destroy instance or other finalize method.
  46. /// </summary>
  47. protected virtual void OnClear(T instance)
  48. {
  49. if (instance == null) return;
  50. var go = instance.gameObject;
  51. if (go == null) return;
  52. UnityEngine.Object.Destroy(go);
  53. }
  54. /// <summary>
  55. /// Current pooled object count.
  56. /// </summary>
  57. public int Count
  58. {
  59. get
  60. {
  61. if (q == null) return 0;
  62. return q.Count;
  63. }
  64. }
  65. /// <summary>
  66. /// Get instance from pool.
  67. /// </summary>
  68. public T Rent()
  69. {
  70. if (isDisposed) throw new ObjectDisposedException("ObjectPool was already disposed.");
  71. if (q == null) q = new Queue<T>();
  72. var instance = (q.Count > 0)
  73. ? q.Dequeue()
  74. : CreateInstance();
  75. OnBeforeRent(instance);
  76. return instance;
  77. }
  78. /// <summary>
  79. /// Return instance to pool.
  80. /// </summary>
  81. public void Return(T instance)
  82. {
  83. if (isDisposed) throw new ObjectDisposedException("ObjectPool was already disposed.");
  84. if (instance == null) throw new ArgumentNullException("instance");
  85. if (q == null) q = new Queue<T>();
  86. if ((q.Count + 1) == MaxPoolCount)
  87. {
  88. throw new InvalidOperationException("Reached Max PoolSize");
  89. }
  90. OnBeforeReturn(instance);
  91. q.Enqueue(instance);
  92. }
  93. /// <summary>
  94. /// Clear pool.
  95. /// </summary>
  96. public void Clear(bool callOnBeforeRent = false)
  97. {
  98. if (q == null) return;
  99. while (q.Count != 0)
  100. {
  101. var instance = q.Dequeue();
  102. if (callOnBeforeRent)
  103. {
  104. OnBeforeRent(instance);
  105. }
  106. OnClear(instance);
  107. }
  108. }
  109. /// <summary>
  110. /// Trim pool instances.
  111. /// </summary>
  112. /// <param name="instanceCountRatio">0.0f = clear all ~ 1.0f = live all.</param>
  113. /// <param name="minSize">Min pool count.</param>
  114. /// <param name="callOnBeforeRent">If true, call OnBeforeRent before OnClear.</param>
  115. public void Shrink(float instanceCountRatio, int minSize, bool callOnBeforeRent = false)
  116. {
  117. if (q == null) return;
  118. if (instanceCountRatio <= 0) instanceCountRatio = 0;
  119. if (instanceCountRatio >= 1.0f) instanceCountRatio = 1.0f;
  120. var size = (int)(q.Count * instanceCountRatio);
  121. size = Math.Max(minSize, size);
  122. while (q.Count > size)
  123. {
  124. var instance = q.Dequeue();
  125. if (callOnBeforeRent)
  126. {
  127. OnBeforeRent(instance);
  128. }
  129. OnClear(instance);
  130. }
  131. }
  132. /// <summary>
  133. /// If needs shrink pool frequently, start check timer.
  134. /// </summary>
  135. /// <param name="checkInterval">Interval of call Shrink.</param>
  136. /// <param name="instanceCountRatio">0.0f = clearAll ~ 1.0f = live all.</param>
  137. /// <param name="minSize">Min pool count.</param>
  138. /// <param name="callOnBeforeRent">If true, call OnBeforeRent before OnClear.</param>
  139. public IDisposable StartShrinkTimer(TimeSpan checkInterval, float instanceCountRatio, int minSize, bool callOnBeforeRent = false)
  140. {
  141. return Observable.Interval(checkInterval)
  142. .TakeWhile(_ => !isDisposed)
  143. .Subscribe(_ =>
  144. {
  145. Shrink(instanceCountRatio, minSize, callOnBeforeRent);
  146. });
  147. }
  148. /// <summary>
  149. /// Fill pool before rent operation.
  150. /// </summary>
  151. /// <param name="preloadCount">Pool instance count.</param>
  152. /// <param name="threshold">Create count per frame.</param>
  153. public IObservable<Unit> PreloadAsync(int preloadCount, int threshold)
  154. {
  155. if (q == null) q = new Queue<T>(preloadCount);
  156. return Observable.FromMicroCoroutine<Unit>((observer, cancel) => PreloadCore(preloadCount, threshold, observer, cancel));
  157. }
  158. IEnumerator PreloadCore(int preloadCount, int threshold, IObserver<Unit> observer, CancellationToken cancellationToken)
  159. {
  160. while (Count < preloadCount && !cancellationToken.IsCancellationRequested)
  161. {
  162. var requireCount = preloadCount - Count;
  163. if (requireCount <= 0) break;
  164. var createCount = Math.Min(requireCount, threshold);
  165. for (int i = 0; i < createCount; i++)
  166. {
  167. try
  168. {
  169. var instance = CreateInstance();
  170. Return(instance);
  171. }
  172. catch (Exception ex)
  173. {
  174. observer.OnError(ex);
  175. yield break;
  176. }
  177. }
  178. yield return null; // next frame.
  179. }
  180. observer.OnNext(Unit.Default);
  181. observer.OnCompleted();
  182. }
  183. #region IDisposable Support
  184. protected virtual void Dispose(bool disposing)
  185. {
  186. if (!isDisposed)
  187. {
  188. if (disposing)
  189. {
  190. Clear(false);
  191. }
  192. isDisposed = true;
  193. }
  194. }
  195. public void Dispose()
  196. {
  197. Dispose(true);
  198. }
  199. #endregion
  200. }
  201. /// <summary>
  202. /// Bass class of ObjectPool. If needs asynchronous initialization, use this instead of standard ObjectPool.
  203. /// </summary>
  204. public abstract class AsyncObjectPool<T> : IDisposable
  205. where T : UnityEngine.Component
  206. {
  207. bool isDisposed = false;
  208. Queue<T> q;
  209. /// <summary>
  210. /// Limit of instace count.
  211. /// </summary>
  212. protected int MaxPoolCount
  213. {
  214. get
  215. {
  216. return int.MaxValue;
  217. }
  218. }
  219. /// <summary>
  220. /// Create instance when needed.
  221. /// </summary>
  222. protected abstract IObservable<T> CreateInstanceAsync();
  223. /// <summary>
  224. /// Called before return to pool, useful for set active object(it is default behavior).
  225. /// </summary>
  226. protected virtual void OnBeforeRent(T instance)
  227. {
  228. instance.gameObject.SetActive(true);
  229. }
  230. /// <summary>
  231. /// Called before return to pool, useful for set inactive object(it is default behavior).
  232. /// </summary>
  233. protected virtual void OnBeforeReturn(T instance)
  234. {
  235. instance.gameObject.SetActive(false);
  236. }
  237. /// <summary>
  238. /// Called when clear or disposed, useful for destroy instance or other finalize method.
  239. /// </summary>
  240. protected virtual void OnClear(T instance)
  241. {
  242. if (instance == null) return;
  243. var go = instance.gameObject;
  244. if (go == null) return;
  245. UnityEngine.Object.Destroy(go);
  246. }
  247. /// <summary>
  248. /// Current pooled object count.
  249. /// </summary>
  250. public int Count
  251. {
  252. get
  253. {
  254. if (q == null) return 0;
  255. return q.Count;
  256. }
  257. }
  258. /// <summary>
  259. /// Get instance from pool.
  260. /// </summary>
  261. public IObservable<T> RentAsync()
  262. {
  263. if (isDisposed) throw new ObjectDisposedException("ObjectPool was already disposed.");
  264. if (q == null) q = new Queue<T>();
  265. if (q.Count > 0)
  266. {
  267. var instance = q.Dequeue();
  268. OnBeforeRent(instance);
  269. return Observable.Return(instance);
  270. }
  271. else
  272. {
  273. var instance = CreateInstanceAsync();
  274. return instance.Do(x => OnBeforeRent(x));
  275. }
  276. }
  277. /// <summary>
  278. /// Return instance to pool.
  279. /// </summary>
  280. public void Return(T instance)
  281. {
  282. if (isDisposed) throw new ObjectDisposedException("ObjectPool was already disposed.");
  283. if (instance == null) throw new ArgumentNullException("instance");
  284. if (q == null) q = new Queue<T>();
  285. if ((q.Count + 1) == MaxPoolCount)
  286. {
  287. throw new InvalidOperationException("Reached Max PoolSize");
  288. }
  289. OnBeforeReturn(instance);
  290. q.Enqueue(instance);
  291. }
  292. /// <summary>
  293. /// Trim pool instances.
  294. /// </summary>
  295. /// <param name="instanceCountRatio">0.0f = clear all ~ 1.0f = live all.</param>
  296. /// <param name="minSize">Min pool count.</param>
  297. /// <param name="callOnBeforeRent">If true, call OnBeforeRent before OnClear.</param>
  298. public void Shrink(float instanceCountRatio, int minSize, bool callOnBeforeRent = false)
  299. {
  300. if (q == null) return;
  301. if (instanceCountRatio <= 0) instanceCountRatio = 0;
  302. if (instanceCountRatio >= 1.0f) instanceCountRatio = 1.0f;
  303. var size = (int)(q.Count * instanceCountRatio);
  304. size = Math.Max(minSize, size);
  305. while (q.Count > size)
  306. {
  307. var instance = q.Dequeue();
  308. if (callOnBeforeRent)
  309. {
  310. OnBeforeRent(instance);
  311. }
  312. OnClear(instance);
  313. }
  314. }
  315. /// <summary>
  316. /// If needs shrink pool frequently, start check timer.
  317. /// </summary>
  318. /// <param name="checkInterval">Interval of call Shrink.</param>
  319. /// <param name="instanceCountRatio">0.0f = clearAll ~ 1.0f = live all.</param>
  320. /// <param name="minSize">Min pool count.</param>
  321. /// <param name="callOnBeforeRent">If true, call OnBeforeRent before OnClear.</param>
  322. public IDisposable StartShrinkTimer(TimeSpan checkInterval, float instanceCountRatio, int minSize, bool callOnBeforeRent = false)
  323. {
  324. return Observable.Interval(checkInterval)
  325. .TakeWhile(_ => !isDisposed)
  326. .Subscribe(_ =>
  327. {
  328. Shrink(instanceCountRatio, minSize, callOnBeforeRent);
  329. });
  330. }
  331. /// <summary>
  332. /// Clear pool.
  333. /// </summary>
  334. public void Clear(bool callOnBeforeRent = false)
  335. {
  336. if (q == null) return;
  337. while (q.Count != 0)
  338. {
  339. var instance = q.Dequeue();
  340. if (callOnBeforeRent)
  341. {
  342. OnBeforeRent(instance);
  343. }
  344. OnClear(instance);
  345. }
  346. }
  347. /// <summary>
  348. /// Fill pool before rent operation.
  349. /// </summary>
  350. /// <param name="preloadCount">Pool instance count.</param>
  351. /// <param name="threshold">Create count per frame.</param>
  352. public IObservable<Unit> PreloadAsync(int preloadCount, int threshold)
  353. {
  354. if (q == null) q = new Queue<T>(preloadCount);
  355. return Observable.FromMicroCoroutine<Unit>((observer, cancel) => PreloadCore(preloadCount, threshold, observer, cancel));
  356. }
  357. IEnumerator PreloadCore(int preloadCount, int threshold, IObserver<Unit> observer, CancellationToken cancellationToken)
  358. {
  359. while (Count < preloadCount && !cancellationToken.IsCancellationRequested)
  360. {
  361. var requireCount = preloadCount - Count;
  362. if (requireCount <= 0) break;
  363. var createCount = Math.Min(requireCount, threshold);
  364. var loaders = new IObservable<Unit>[createCount];
  365. for (int i = 0; i < createCount; i++)
  366. {
  367. var instanceFuture = CreateInstanceAsync();
  368. loaders[i] = instanceFuture.ForEachAsync(x => Return(x));
  369. }
  370. var awaiter = Observable.WhenAll(loaders).ToYieldInstruction(false, cancellationToken);
  371. while (!(awaiter.HasResult || awaiter.IsCanceled || awaiter.HasError))
  372. {
  373. yield return null;
  374. }
  375. if (awaiter.HasError)
  376. {
  377. observer.OnError(awaiter.Error);
  378. yield break;
  379. }
  380. else if (awaiter.IsCanceled)
  381. {
  382. yield break; // end.
  383. }
  384. }
  385. observer.OnNext(Unit.Default);
  386. observer.OnCompleted();
  387. }
  388. #region IDisposable Support
  389. protected virtual void Dispose(bool disposing)
  390. {
  391. if (!isDisposed)
  392. {
  393. if (disposing)
  394. {
  395. Clear(false);
  396. }
  397. isDisposed = true;
  398. }
  399. }
  400. public void Dispose()
  401. {
  402. Dispose(true);
  403. }
  404. #endregion
  405. }
  406. }
  407. #endif