PrimitiveBatch.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. #region File Description
  2. //-----------------------------------------------------------------------------
  3. // PrimitiveBatch.cs
  4. //
  5. // Microsoft XNA Community Game Platform
  6. // Copyright (C) Microsoft Corporation. All rights reserved.
  7. //-----------------------------------------------------------------------------
  8. #endregion
  9. #region Using Statements
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Text;
  13. using Microsoft.Xna.Framework;
  14. using Microsoft.Xna.Framework.Graphics;
  15. using Microsoft.Xna.Framework.Content;
  16. using Microsoft.Xna.Framework.Input;
  17. #endregion
  18. namespace PrimitivesSample
  19. {
  20. // PrimitiveBatch is a class that handles efficient rendering automatically for its
  21. // users, in a similar way to SpriteBatch. PrimitiveBatch can render lines, points,
  22. // and triangles to the screen. In this sample, it is used to draw a spacewars
  23. // retro scene.
  24. public class PrimitiveBatch : IDisposable
  25. {
  26. #region Constants and Fields
  27. // this constant controls how large the vertices buffer is. Larger buffers will
  28. // require flushing less often, which can increase performance. However, having
  29. // buffer that is unnecessarily large will waste memory.
  30. const int DefaultBufferSize = 500;
  31. // a block of vertices that calling AddVertex will fill. Flush will draw using
  32. // this array, and will determine how many primitives to draw from
  33. // positionInBuffer.
  34. VertexPositionColor[] vertices = new VertexPositionColor[DefaultBufferSize];
  35. // keeps track of how many vertices have been added. this value increases until
  36. // we run out of space in the buffer, at which time Flush is automatically
  37. // called.
  38. int positionInBuffer = 0;
  39. // a basic effect, which contains the shaders that we will use to draw our
  40. // primitives.
  41. BasicEffect basicEffect;
  42. // the device that we will issue draw calls to.
  43. GraphicsDevice device;
  44. // this value is set by Begin, and is the type of primitives that we are
  45. // drawing.
  46. PrimitiveType primitiveType;
  47. // how many verts does each of these primitives take up? points are 1,
  48. // lines are 2, and triangles are 3.
  49. int numVertsPerPrimitive;
  50. // hasBegun is flipped to true once Begin is called, and is used to make
  51. // sure users don't call End before Begin is called.
  52. bool hasBegun = false;
  53. bool isDisposed = false;
  54. #endregion
  55. // the constructor creates a new PrimitiveBatch and sets up all of the internals
  56. // that PrimitiveBatch will need.
  57. public PrimitiveBatch(GraphicsDevice graphicsDevice)
  58. {
  59. if (graphicsDevice == null)
  60. {
  61. throw new ArgumentNullException("graphicsDevice");
  62. }
  63. device = graphicsDevice;
  64. // set up a new basic effect, and enable vertex colors.
  65. basicEffect = new BasicEffect(graphicsDevice);
  66. basicEffect.VertexColorEnabled = true;
  67. // projection uses CreateOrthographicOffCenter to create 2d projection
  68. // matrix with 0,0 in the upper left.
  69. basicEffect.Projection = Matrix.CreateOrthographicOffCenter
  70. (0, graphicsDevice.Viewport.Width,
  71. graphicsDevice.Viewport.Height, 0,
  72. 0, 1);
  73. this.basicEffect.World = Matrix.Identity;
  74. this.basicEffect.View = Matrix.CreateLookAt(Vector3.Zero, Vector3.Forward,
  75. Vector3.Up);
  76. }
  77. public void Dispose()
  78. {
  79. this.Dispose(true);
  80. GC.SuppressFinalize(this);
  81. }
  82. protected virtual void Dispose(bool disposing)
  83. {
  84. if (disposing && !isDisposed)
  85. {
  86. if (basicEffect != null)
  87. basicEffect.Dispose();
  88. isDisposed = true;
  89. }
  90. }
  91. // Begin is called to tell the PrimitiveBatch what kind of primitives will be
  92. // drawn, and to prepare the graphics card to render those primitives.
  93. public void Begin(PrimitiveType primitiveType)
  94. {
  95. if (hasBegun)
  96. {
  97. throw new InvalidOperationException
  98. ("End must be called before Begin can be called again.");
  99. }
  100. // these three types reuse vertices, so we can't flush properly without more
  101. // complex logic. Since that's a bit too complicated for this sample, we'll
  102. // simply disallow them.
  103. if (primitiveType == PrimitiveType.LineStrip ||
  104. primitiveType == PrimitiveType.TriangleStrip)
  105. {
  106. throw new NotSupportedException
  107. ("The specified primitiveType is not supported by PrimitiveBatch.");
  108. }
  109. this.primitiveType = primitiveType;
  110. // how many verts will each of these primitives require?
  111. this.numVertsPerPrimitive = NumVertsPerPrimitive(primitiveType);
  112. //tell our basic effect to begin.
  113. basicEffect.CurrentTechnique.Passes[0].Apply();
  114. // flip the error checking boolean. It's now ok to call AddVertex, Flush,
  115. // and End.
  116. hasBegun = true;
  117. }
  118. // AddVertex is called to add another vertex to be rendered. To draw a point,
  119. // AddVertex must be called once. for lines, twice, and for triangles 3 times.
  120. // this function can only be called once begin has been called.
  121. // if there is not enough room in the vertices buffer, Flush is called
  122. // automatically.
  123. public void AddVertex(Vector2 vertex, Color color)
  124. {
  125. if (!hasBegun)
  126. {
  127. throw new InvalidOperationException
  128. ("Begin must be called before AddVertex can be called.");
  129. }
  130. // are we starting a new primitive? if so, and there will not be enough room
  131. // for a whole primitive, flush.
  132. bool newPrimitive = ((positionInBuffer % numVertsPerPrimitive) == 0);
  133. if (newPrimitive &&
  134. (positionInBuffer + numVertsPerPrimitive) >= vertices.Length)
  135. {
  136. Flush();
  137. }
  138. // once we know there's enough room, set the vertex in the buffer,
  139. // and increase position.
  140. vertices[positionInBuffer].Position = new Vector3(vertex, 0);
  141. vertices[positionInBuffer].Color = color;
  142. positionInBuffer++;
  143. }
  144. // End is called once all the primitives have been drawn using AddVertex.
  145. // it will call Flush to actually submit the draw call to the graphics card, and
  146. // then tell the basic effect to end.
  147. public void End()
  148. {
  149. if (!hasBegun)
  150. {
  151. throw new InvalidOperationException
  152. ("Begin must be called before End can be called.");
  153. }
  154. // Draw whatever the user wanted us to draw
  155. Flush();
  156. hasBegun = false;
  157. }
  158. // Flush is called to issue the draw call to the graphics card. Once the draw
  159. // call is made, positionInBuffer is reset, so that AddVertex can start over
  160. // at the beginning. End will call this to draw the primitives that the user
  161. // requested, and AddVertex will call this if there is not enough room in the
  162. // buffer.
  163. private void Flush()
  164. {
  165. if (!hasBegun)
  166. {
  167. throw new InvalidOperationException
  168. ("Begin must be called before Flush can be called.");
  169. }
  170. // no work to do
  171. if (positionInBuffer == 0)
  172. {
  173. return;
  174. }
  175. // how many primitives will we draw?
  176. int primitiveCount = positionInBuffer / numVertsPerPrimitive;
  177. // submit the draw call to the graphics card
  178. device.DrawUserPrimitives<VertexPositionColor>(primitiveType, vertices, 0,
  179. primitiveCount);
  180. // now that we've drawn, it's ok to reset positionInBuffer back to zero,
  181. // and write over any vertices that may have been set previously.
  182. positionInBuffer = 0;
  183. }
  184. #region Helper functions
  185. // NumVertsPerPrimitive is a boring helper function that tells how many vertices
  186. // it will take to draw each kind of primitive.
  187. static private int NumVertsPerPrimitive(PrimitiveType primitive)
  188. {
  189. int numVertsPerPrimitive;
  190. switch (primitive)
  191. {
  192. case PrimitiveType.LineList:
  193. numVertsPerPrimitive = 2;
  194. break;
  195. case PrimitiveType.TriangleList:
  196. numVertsPerPrimitive = 3;
  197. break;
  198. default:
  199. throw new InvalidOperationException("primitive is not valid");
  200. }
  201. return numVertsPerPrimitive;
  202. }
  203. #endregion
  204. }
  205. }