Batcher.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. using System;
  2. using System.Runtime.CompilerServices;
  3. using Microsoft.Xna.Framework;
  4. using Microsoft.Xna.Framework.Graphics;
  5. namespace MonoGame.Extended.Graphics
  6. {
  7. /// <summary>
  8. /// Minimizes draw calls to a <see cref="GraphicsDevice" /> by sorting them and attempting to merge them together
  9. /// before submitting them.
  10. /// </summary>
  11. /// <typeparam name="TDrawCallInfo">The type of the information for a draw call.</typeparam>
  12. /// <seealso cref="IDisposable" />
  13. public abstract class Batcher<TDrawCallInfo> : IDisposable
  14. where TDrawCallInfo : struct, IBatchDrawCallInfo<TDrawCallInfo>, IComparable<TDrawCallInfo>
  15. {
  16. internal const int DefaultBatchMaximumDrawCallsCount = 2048;
  17. private BlendState _blendState;
  18. private SamplerState _samplerState;
  19. private DepthStencilState _depthStencilState;
  20. private RasterizerState _rasterizerState;
  21. private readonly Effect _defaultEffect;
  22. private Effect _currentEffect;
  23. private Matrix? _viewMatrix;
  24. private Matrix? _projectionMatrix;
  25. /// <summary>
  26. /// The array of <see cref="TDrawCallInfo" /> structs currently enqueued.
  27. /// </summary>
  28. protected TDrawCallInfo[] DrawCalls;
  29. /// <summary>
  30. /// The number of <see cref="TDrawCallInfo" /> structs currently enqueued.
  31. /// </summary>
  32. protected int EnqueuedDrawCallCount;
  33. /// <summary>
  34. /// Gets the <see cref="GraphicsDevice" /> associated with this <see cref="Batcher{TDrawCallInfo}" />.
  35. /// </summary>
  36. /// <value>
  37. /// The <see cref="GraphicsDevice" /> associated with this <see cref="Batcher{TDrawCallInfo}" />.
  38. /// </value>
  39. public GraphicsDevice GraphicsDevice { get; }
  40. /// <summary>
  41. /// Gets a value indicating whether batching is currently in progress by being within a <see cref="Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> and
  42. /// <see cref="End" /> pair block of code.
  43. /// </summary>
  44. /// <value>
  45. /// <c>true</c> if batching has begun; otherwise, <c>false</c>.
  46. /// </value>
  47. public bool HasBegun { get; internal set; }
  48. /// <summary>
  49. /// Initializes a new instance of the <see cref="Batcher{TDrawCallInfo}" /> class.
  50. /// </summary>
  51. /// <param name="graphicsDevice">The graphics device.</param>
  52. /// <param name="defaultEffect">The default effect.</param>
  53. /// <param name="maximumDrawCallsCount">
  54. /// The maximum number of <see cref="TDrawCallInfo" /> structs that can be enqueued before a
  55. /// <see cref="Batcher{TDrawCallInfo}.Flush" />
  56. /// is required. The default value is <code>2048</code>.
  57. /// </param>
  58. /// <exception cref="ArgumentNullException">
  59. /// <paramref name="graphicsDevice" /> is
  60. /// null.
  61. /// </exception>
  62. /// <exception cref="ArgumentOutOfRangeException">
  63. /// <paramref name="maximumDrawCallsCount" /> is less than or equal
  64. /// <code>0</code>.
  65. /// </exception>
  66. protected Batcher(GraphicsDevice graphicsDevice, Effect defaultEffect,
  67. int maximumDrawCallsCount = DefaultBatchMaximumDrawCallsCount)
  68. {
  69. if (graphicsDevice == null)
  70. throw new ArgumentNullException(nameof(graphicsDevice));
  71. if (maximumDrawCallsCount <= 0)
  72. throw new ArgumentOutOfRangeException(nameof(maximumDrawCallsCount));
  73. GraphicsDevice = graphicsDevice;
  74. _defaultEffect = defaultEffect;
  75. DrawCalls = new TDrawCallInfo[maximumDrawCallsCount];
  76. }
  77. /// <summary>
  78. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  79. /// </summary>
  80. public void Dispose()
  81. {
  82. Dispose(true);
  83. GC.SuppressFinalize(this);
  84. }
  85. /// <summary>
  86. /// Releases unmanaged and - optionally - managed resources.
  87. /// </summary>
  88. /// <param name="diposing">
  89. /// <c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only
  90. /// unmanaged resources.
  91. /// </param>
  92. protected virtual void Dispose(bool diposing)
  93. {
  94. if (!diposing)
  95. return;
  96. _defaultEffect.Dispose();
  97. }
  98. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  99. protected void EnsureHasBegun([CallerMemberName] string callerMemberName = null)
  100. {
  101. if (!HasBegun)
  102. throw new InvalidOperationException(
  103. $"The {nameof(Begin)} method must be called before the {callerMemberName} method can be called.");
  104. }
  105. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  106. protected void EnsureHasNotBegun([CallerMemberName] string callerMemberName = null)
  107. {
  108. if (HasBegun)
  109. throw new InvalidOperationException(
  110. $"The {nameof(End)} method must be called before the {callerMemberName} method can be called.");
  111. }
  112. /// <summary>
  113. /// Begins the batch operation using an optional <see cref="BlendState" />, <see cref="SamplerState" />,
  114. /// <see cref="DepthStencilState" />, <see cref="RasterizerState" />, <see cref="Effect" />, world-to-view
  115. /// <see cref="Matrix" />, or view-to-projection <see cref="Matrix" />.
  116. /// </summary>
  117. /// <remarks>
  118. /// <para>
  119. /// The default objects for <paramref name="blendState" />, <paramref name="samplerState" />,
  120. /// <paramref name="depthStencilState" />, and <paramref name="rasterizerState" /> are
  121. /// <see cref="BlendState.AlphaBlend" />, <see cref="SamplerState.LinearClamp" />,
  122. /// <see cref="DepthStencilState.None" /> and <see cref="RasterizerState.CullCounterClockwise" /> respectively.
  123. /// Passing
  124. /// <code>null</code> for any of the previously mentioned parameters result in using their default object.
  125. /// </para>
  126. /// </remarks>
  127. /// <param name="blendState">The <see cref="BlendState" /> to use for the <see cref="Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" />, <see cref="End" /> pair.</param>
  128. /// <param name="samplerState">
  129. /// The texture <see cref="SamplerState" /> to use for the <see cref="Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> and
  130. /// <see cref="End" /> pair.
  131. /// </param>
  132. /// <param name="depthStencilState">
  133. /// The <see cref="DepthStencilState" /> to use for the <see cref="Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> and
  134. /// <see cref="End" /> pair.
  135. /// </param>
  136. /// <param name="rasterizerState">
  137. /// The <see cref="RasterizerState" /> to use for the <see cref="Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> and
  138. /// <see cref="End" /> pair.
  139. /// </param>
  140. /// <param name="effect">The <see cref="Effect" /> to use for the <see cref="Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> and <see cref="End" /> pair.</param>
  141. /// <param name="viewMatrix">
  142. /// The world-to-view transformation matrix to use for the <see cref="Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> and
  143. /// <see cref="End" /> pair.
  144. /// </param>
  145. /// <param name="projectionMatrix">
  146. /// The view-to-projection transformation matrix to use for the <see cref="Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> and
  147. /// <see cref="End" /> pair.
  148. /// </param>
  149. /// <exception cref="InvalidOperationException">
  150. /// <see cref="Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> cannot be invoked again until <see cref="End" /> has been invoked.
  151. /// </exception>
  152. /// <remarks>
  153. /// <para>
  154. /// This method must be called before any enqueuing of draw calls. When all the geometry have been enqueued for
  155. /// drawing, call <see cref="End" />.
  156. /// </para>
  157. /// </remarks>
  158. public virtual void Begin(Matrix? viewMatrix = null, Matrix? projectionMatrix = null, BlendState blendState = null, SamplerState samplerState = null,
  159. DepthStencilState depthStencilState = null, RasterizerState rasterizerState = null, Effect effect = null)
  160. {
  161. var viewMatrix1 = viewMatrix ?? Matrix.Identity;
  162. var projectionMatrix1 = projectionMatrix ?? Matrix.CreateOrthographicOffCenter(0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 0, -1);
  163. Begin(ref viewMatrix1, ref projectionMatrix1, blendState, samplerState, depthStencilState, rasterizerState, effect);
  164. }
  165. /// <summary>
  166. /// Begins the batch operation using an optional <see cref="BlendState" />, <see cref="SamplerState" />,
  167. /// <see cref="DepthStencilState" />, <see cref="RasterizerState" />, <see cref="Effect" />, world-to-view
  168. /// <see cref="Matrix" />, or view-to-projection <see cref="Matrix" />.
  169. /// </summary>
  170. /// <remarks>
  171. /// <para>
  172. /// The default objects for <paramref name="blendState" />, <paramref name="samplerState" />,
  173. /// <paramref name="depthStencilState" />, and <paramref name="rasterizerState" /> are
  174. /// <see cref="BlendState.AlphaBlend" />, <see cref="SamplerState.LinearClamp" />,
  175. /// <see cref="DepthStencilState.None" /> and <see cref="RasterizerState.CullCounterClockwise" /> respectively.
  176. /// Passing
  177. /// <code>null</code> for any of the previously mentioned parameters result in using their default object.
  178. /// </para>
  179. /// </remarks>
  180. /// <param name="blendState">The <see cref="BlendState" /> to use for the <see cref="Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" />, <see cref="End" /> pair.</param>
  181. /// <param name="samplerState">
  182. /// The texture <see cref="SamplerState" /> to use for the <see cref="Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> and
  183. /// <see cref="End" /> pair.
  184. /// </param>
  185. /// <param name="depthStencilState">
  186. /// The <see cref="DepthStencilState" /> to use for the <see cref="Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> and
  187. /// <see cref="End" /> pair.
  188. /// </param>
  189. /// <param name="rasterizerState">
  190. /// The <see cref="RasterizerState" /> to use for the <see cref="Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> and
  191. /// <see cref="End" /> pair.
  192. /// </param>
  193. /// <param name="effect">The <see cref="Effect" /> to use for the <see cref="Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> and <see cref="End" /> pair.</param>
  194. /// <param name="viewMatrix">
  195. /// The world-to-view transformation matrix to use for the <see cref="Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> and
  196. /// <see cref="End" /> pair.
  197. /// </param>
  198. /// <param name="projectionMatrix">
  199. /// The view-to-projection transformation matrix to use for the <see cref="Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> and
  200. /// <see cref="End" /> pair.
  201. /// </param>
  202. /// <exception cref="InvalidOperationException">
  203. /// <see cref="Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> cannot be invoked again until <see cref="End" /> has been invoked.
  204. /// </exception>
  205. /// <remarks>
  206. /// <para>
  207. /// This method must be called before any enqueuing of draw calls. When all the geometry have been enqueued for
  208. /// drawing, call <see cref="End" />.
  209. /// </para>
  210. /// </remarks>
  211. public virtual void Begin(ref Matrix viewMatrix, ref Matrix projectionMatrix, BlendState blendState = null, SamplerState samplerState = null,
  212. DepthStencilState depthStencilState = null, RasterizerState rasterizerState = null, Effect effect = null)
  213. {
  214. EnsureHasNotBegun();
  215. HasBegun = true;
  216. // Store the states to be applied on End()
  217. // This ensures that two or more batchers will not affect each other
  218. _blendState = blendState ?? BlendState.AlphaBlend;
  219. _samplerState = samplerState ?? SamplerState.PointClamp;
  220. _depthStencilState = depthStencilState ?? DepthStencilState.None;
  221. _rasterizerState = rasterizerState ?? RasterizerState.CullCounterClockwise;
  222. _currentEffect = effect ?? _defaultEffect;
  223. _projectionMatrix = projectionMatrix;
  224. _viewMatrix = viewMatrix;
  225. }
  226. /// <summary>
  227. /// Flushes the batched geometry to the <see cref="GraphicsDevice" /> and restores it's state to how it was before
  228. /// <see cref="Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> was called.
  229. /// </summary>
  230. /// <exception cref="InvalidOperationException">
  231. /// <see cref="End" /> cannot be invoked until <see cref="Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> has been invoked.
  232. /// </exception>
  233. /// <remarks>
  234. /// <para>
  235. /// This method must be called after all enqueuing of draw calls.
  236. /// </para>
  237. /// </remarks>
  238. public void End()
  239. {
  240. EnsureHasBegun();
  241. Flush();
  242. HasBegun = false;
  243. }
  244. /// <summary>
  245. /// Sorts then submits the (sorted) enqueued draw calls to the <see cref="GraphicsDevice" /> for
  246. /// rendering without ending the <see cref="Begin(ref Matrix, ref Matrix, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect)" /> and <see cref="End" /> pair.
  247. /// </summary>
  248. protected void Flush()
  249. {
  250. if (EnqueuedDrawCallCount == 0)
  251. return;
  252. SortDrawCallsAndBindBuffers();
  253. ApplyStates();
  254. SubmitDrawCalls();
  255. RestoreStates();
  256. }
  257. /// <summary>
  258. /// Sorts the enqueued draw calls and binds any used <see cref="VertexBuffer" /> or <see cref="IndexBuffer" /> to the <see cref="GraphicsDevice" />.
  259. /// </summary>
  260. protected abstract void SortDrawCallsAndBindBuffers();
  261. private void ApplyStates()
  262. {
  263. var oldBlendState = GraphicsDevice.BlendState;
  264. var oldSamplerState = GraphicsDevice.SamplerStates[0];
  265. var oldDepthStencilState = GraphicsDevice.DepthStencilState;
  266. var oldRasterizerState = GraphicsDevice.RasterizerState;
  267. GraphicsDevice.BlendState = _blendState;
  268. GraphicsDevice.SamplerStates[0] = _samplerState;
  269. GraphicsDevice.DepthStencilState = _depthStencilState;
  270. GraphicsDevice.RasterizerState = _rasterizerState;
  271. _blendState = oldBlendState;
  272. _samplerState = oldSamplerState;
  273. _depthStencilState = oldDepthStencilState;
  274. _rasterizerState = oldRasterizerState;
  275. var viewMatrix = _viewMatrix ?? Matrix.Identity;
  276. var projectionMatrix = _projectionMatrix ??
  277. Matrix.CreateOrthographicOffCenter(0, GraphicsDevice.Viewport.Width,
  278. GraphicsDevice.Viewport.Height, 0, 0f, -1f);
  279. var matrixChainEffect = _currentEffect as IMatrixChainEffect;
  280. if (matrixChainEffect != null)
  281. {
  282. matrixChainEffect.World = Matrix.Identity;
  283. matrixChainEffect.SetView(ref viewMatrix);
  284. matrixChainEffect.SetProjection(ref projectionMatrix);
  285. }
  286. else
  287. {
  288. var effectMatrices = _currentEffect as IEffectMatrices;
  289. if (effectMatrices == null)
  290. return;
  291. effectMatrices.World = Matrix.Identity;
  292. effectMatrices.View = viewMatrix;
  293. effectMatrices.Projection = projectionMatrix;
  294. }
  295. }
  296. private void RestoreStates()
  297. {
  298. GraphicsDevice.BlendState = _blendState;
  299. GraphicsDevice.SamplerStates[0] = _samplerState;
  300. GraphicsDevice.DepthStencilState = _depthStencilState;
  301. GraphicsDevice.RasterizerState = _rasterizerState;
  302. }
  303. /// <summary>
  304. /// Enqueues draw call information.
  305. /// </summary>
  306. /// <param name="drawCall">The draw call information.</param>
  307. /// <remarks>
  308. /// <para>
  309. /// If possible, the <paramref name="drawCall" /> is merged with the last enqueued draw call information instead of
  310. /// being
  311. /// enqueued.
  312. /// </para>
  313. /// <para>
  314. /// If the enqueue buffer is full, a <see cref="Flush" /> is invoked and then afterwards
  315. /// <paramref name="drawCall" /> is enqueued.
  316. /// </para>
  317. /// </remarks>
  318. protected void Enqueue(ref TDrawCallInfo drawCall)
  319. {
  320. if (EnqueuedDrawCallCount > 0 && drawCall.TryMerge(ref DrawCalls[EnqueuedDrawCallCount - 1]))
  321. return;
  322. if (EnqueuedDrawCallCount >= DrawCalls.Length)
  323. Flush();
  324. DrawCalls[EnqueuedDrawCallCount++] = drawCall;
  325. }
  326. /* It might be better to have derived classes just implement the for loop instead of having this virtual method call...
  327. * However, if the derived class is only going to override this method once and the code is short, which should both be
  328. * true, then maybe we can get away with this virtual method call by having it inlined. So tell the JIT or AOT compiler
  329. * we would like it be so. This does NOT guarantee the compiler will respect our wishes.
  330. */
  331. /// <summary>
  332. /// Submits a draw operation to the <see cref="GraphicsDevice" /> using the specified <see cref="TDrawCallInfo"/>.
  333. /// </summary>
  334. /// <param name="drawCall">The draw call information.</param>
  335. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  336. protected abstract void InvokeDrawCall(ref TDrawCallInfo drawCall);
  337. private void SubmitDrawCalls()
  338. {
  339. if (EnqueuedDrawCallCount == 0)
  340. return;
  341. for (var i = 0; i < EnqueuedDrawCallCount; i++)
  342. {
  343. DrawCalls[i].SetState(_currentEffect);
  344. foreach (var pass in _currentEffect.CurrentTechnique.Passes)
  345. {
  346. pass.Apply();
  347. InvokeDrawCall(ref DrawCalls[i]);
  348. }
  349. }
  350. Array.Clear(DrawCalls, 0, EnqueuedDrawCallCount);
  351. EnqueuedDrawCallCount = 0;
  352. }
  353. }
  354. }