ParticleSystem.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. #region File Description
  2. //-----------------------------------------------------------------------------
  3. // ParticleSystem.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 Microsoft.Xna.Framework;
  12. using Microsoft.Xna.Framework.Content;
  13. using Microsoft.Xna.Framework.Graphics;
  14. using Microsoft.Xna.Framework.Graphics.PackedVector;
  15. #endregion
  16. namespace Particle3DSample
  17. {
  18. /// <summary>
  19. /// The main component in charge of displaying particles.
  20. /// </summary>
  21. public class ParticleSystem : DrawableGameComponent
  22. {
  23. #region Fields
  24. // Name of the XML settings file describing this particle system.
  25. string settingsName;
  26. // Settings class controls the appearance and animation of this particle system.
  27. ParticleSettings settings;
  28. // For loading the effect and particle texture.
  29. ContentManager content;
  30. // Custom effect for drawing particles. This computes the particle
  31. // animation entirely in the vertex shader: no per-particle CPU work required!
  32. Effect particleEffect;
  33. // Shortcuts for accessing frequently changed effect parameters.
  34. EffectParameter effectViewParameter;
  35. EffectParameter effectProjectionParameter;
  36. EffectParameter effectViewportScaleParameter;
  37. EffectParameter effectTimeParameter;
  38. // An array of particles, treated as a circular queue.
  39. ParticleVertex[] particles;
  40. // A vertex buffer holding our particles. This contains the same data as
  41. // the particles array, but copied across to where the GPU can access it.
  42. DynamicVertexBuffer vertexBuffer;
  43. // Index buffer turns sets of four vertices into particle quads (pairs of triangles).
  44. IndexBuffer indexBuffer;
  45. // The particles array and vertex buffer are treated as a circular queue.
  46. // Initially, the entire contents of the array are free, because no particles
  47. // are in use. When a new particle is created, this is allocated from the
  48. // beginning of the array. If more than one particle is created, these will
  49. // always be stored in a consecutive block of array elements. Because all
  50. // particles last for the same amount of time, old particles will always be
  51. // removed in order from the start of this active particle region, so the
  52. // active and free regions will never be intermingled. Because the queue is
  53. // circular, there can be times when the active particle region wraps from the
  54. // end of the array back to the start. The queue uses modulo arithmetic to
  55. // handle these cases. For instance with a four entry queue we could have:
  56. //
  57. // 0
  58. // 1 - first active particle
  59. // 2
  60. // 3 - first free particle
  61. //
  62. // In this case, particles 1 and 2 are active, while 3 and 4 are free.
  63. // Using modulo arithmetic we could also have:
  64. //
  65. // 0
  66. // 1 - first free particle
  67. // 2
  68. // 3 - first active particle
  69. //
  70. // Here, 3 and 0 are active, while 1 and 2 are free.
  71. //
  72. // But wait! The full story is even more complex.
  73. //
  74. // When we create a new particle, we add them to our managed particles array.
  75. // We also need to copy this new data into the GPU vertex buffer, but we don't
  76. // want to do that straight away, because setting new data into a vertex buffer
  77. // can be an expensive operation. If we are going to be adding several particles
  78. // in a single frame, it is faster to initially just store them in our managed
  79. // array, and then later upload them all to the GPU in one single call. So our
  80. // queue also needs a region for storing new particles that have been added to
  81. // the managed array but not yet uploaded to the vertex buffer.
  82. //
  83. // Another issue occurs when old particles are retired. The CPU and GPU run
  84. // asynchronously, so the GPU will often still be busy drawing the previous
  85. // frame while the CPU is working on the next frame. This can cause a
  86. // synchronization problem if an old particle is retired, and then immediately
  87. // overwritten by a new one, because the CPU might try to change the contents
  88. // of the vertex buffer while the GPU is still busy drawing the old data from
  89. // it. Normally the graphics driver will take care of this by waiting until
  90. // the GPU has finished drawing inside the VertexBuffer.SetData call, but we
  91. // don't want to waste time waiting around every time we try to add a new
  92. // particle! To avoid this delay, we can specify the SetDataOptions.NoOverwrite
  93. // flag when we write to the vertex buffer. This basically means "I promise I
  94. // will never try to overwrite any data that the GPU might still be using, so
  95. // you can just go ahead and update the buffer straight away". To keep this
  96. // promise, we must avoid reusing vertices immediately after they are drawn.
  97. //
  98. // So in total, our queue contains four different regions:
  99. //
  100. // Vertices between firstActiveParticle and firstNewParticle are actively
  101. // being drawn, and exist in both the managed particles array and the GPU
  102. // vertex buffer.
  103. //
  104. // Vertices between firstNewParticle and firstFreeParticle are newly created,
  105. // and exist only in the managed particles array. These need to be uploaded
  106. // to the GPU at the start of the next draw call.
  107. //
  108. // Vertices between firstFreeParticle and firstRetiredParticle are free and
  109. // waiting to be allocated.
  110. //
  111. // Vertices between firstRetiredParticle and firstActiveParticle are no longer
  112. // being drawn, but were drawn recently enough that the GPU could still be
  113. // using them. These need to be kept around for a few more frames before they
  114. // can be reallocated.
  115. int firstActiveParticle;
  116. int firstNewParticle;
  117. int firstFreeParticle;
  118. int firstRetiredParticle;
  119. // Store the current time, in seconds.
  120. float currentTime;
  121. // Count how many times Draw has been called. This is used to know
  122. // when it is safe to retire old particles back into the free list.
  123. int drawCounter;
  124. // Shared random number generator.
  125. static Random random = new Random ();
  126. #endregion
  127. #region Initialization
  128. /// <summary>
  129. /// Constructor.
  130. /// </summary>
  131. public ParticleSystem (Game game,ContentManager content,string settingsName)
  132. : base(game)
  133. {
  134. this.content = content;
  135. this.settingsName = settingsName;
  136. }
  137. /// <summary>
  138. /// Loads graphics for the particle system.
  139. /// </summary>
  140. protected override void LoadContent ()
  141. {
  142. //return;
  143. settings = content.Load<ParticleSettings> (settingsName);
  144. // Allocate the particle array, and fill in the corner fields (which never change).
  145. particles = new ParticleVertex[settings.MaxParticles * 4];
  146. for (int i = 0; i < settings.MaxParticles; i++) {
  147. particles [i * 4 + 0].Corner = new Short2 (-1, -1);
  148. particles [i * 4 + 1].Corner = new Short2 (1, -1);
  149. particles [i * 4 + 2].Corner = new Short2 (1, 1);
  150. particles [i * 4 + 3].Corner = new Short2 (-1, 1);
  151. }
  152. LoadParticleEffect ();
  153. // Create a dynamic vertex buffer.
  154. vertexBuffer = new DynamicVertexBuffer (GraphicsDevice, ParticleVertex.VertexDeclaration,
  155. settings.MaxParticles * 4, BufferUsage.WriteOnly);
  156. // Create and populate the index buffer.
  157. ushort[] indices = new ushort[settings.MaxParticles * 6];
  158. for (int i = 0; i < settings.MaxParticles; i++) {
  159. indices [i * 6 + 0] = (ushort)(i * 4 + 0);
  160. indices [i * 6 + 1] = (ushort)(i * 4 + 1);
  161. indices [i * 6 + 2] = (ushort)(i * 4 + 2);
  162. indices [i * 6 + 3] = (ushort)(i * 4 + 0);
  163. indices [i * 6 + 4] = (ushort)(i * 4 + 2);
  164. indices [i * 6 + 5] = (ushort)(i * 4 + 3);
  165. }
  166. indexBuffer = new IndexBuffer (GraphicsDevice, typeof(ushort), indices.Length, BufferUsage.WriteOnly);
  167. indexBuffer.SetData (indices);
  168. }
  169. /// <summary>
  170. /// Helper for loading and initializing the particle effect.
  171. /// </summary>
  172. void LoadParticleEffect ()
  173. {
  174. Effect effect = content.Load<Effect> ("ParticleEffect");
  175. // If we have several particle systems, the content manager will return
  176. // a single shared effect instance to them all. But we want to preconfigure
  177. // the effect with parameters that are specific to this particular
  178. // particle system. By cloning the effect, we prevent one particle system
  179. // from stomping over the parameter settings of another.
  180. //particleEffect = effect.Clone ();
  181. // No cloning for now so we will just create a new effect for now
  182. particleEffect = effect;
  183. EffectParameterCollection parameters = particleEffect.Parameters;
  184. // Look up shortcuts for parameters that change every frame.
  185. effectViewParameter = parameters ["View"];
  186. effectProjectionParameter = parameters ["Projection"];
  187. effectViewportScaleParameter = parameters ["ViewportScale"];
  188. effectTimeParameter = parameters ["CurrentTime"];
  189. // Set the values of parameters that do not change.
  190. parameters ["Duration"].SetValue ((float)settings.Duration.TotalSeconds);
  191. parameters ["DurationRandomness"].SetValue (settings.DurationRandomness);
  192. parameters ["Gravity"].SetValue (settings.Gravity);
  193. parameters ["EndVelocity"].SetValue (settings.EndVelocity);
  194. parameters ["MinColor"].SetValue (settings.MinColor.ToVector4 ());
  195. parameters ["MaxColor"].SetValue (settings.MaxColor.ToVector4 ());
  196. parameters ["RotateSpeed"].SetValue (
  197. new Vector2 (settings.MinRotateSpeed, settings.MaxRotateSpeed));
  198. parameters ["StartSize"].SetValue (
  199. new Vector2 (settings.MinStartSize, settings.MaxStartSize));
  200. parameters ["EndSize"].SetValue (
  201. new Vector2 (settings.MinEndSize, settings.MaxEndSize));
  202. // Load the particle texture, and set it onto the effect.
  203. Texture2D texture = content.Load<Texture2D> (settings.TextureName);
  204. parameters ["Texture"].SetValue (texture);
  205. }
  206. #endregion
  207. #region Update and Draw
  208. /// <summary>
  209. /// Updates the particle system.
  210. /// </summary>
  211. public override void Update (GameTime gameTime)
  212. {
  213. if (gameTime == null)
  214. throw new ArgumentNullException ("gameTime");
  215. currentTime += (float)gameTime.ElapsedGameTime.TotalSeconds;
  216. RetireActiveParticles ();
  217. FreeRetiredParticles ();
  218. // If we let our timer go on increasing for ever, it would eventually
  219. // run out of floating point precision, at which point the particles
  220. // would render incorrectly. An easy way to prevent this is to notice
  221. // that the time value doesn't matter when no particles are being drawn,
  222. // so we can reset it back to zero any time the active queue is empty.
  223. if (firstActiveParticle == firstFreeParticle)
  224. currentTime = 0;
  225. if (firstRetiredParticle == firstActiveParticle)
  226. drawCounter = 0;
  227. }
  228. /// <summary>
  229. /// Helper for checking when active particles have reached the end of
  230. /// their life. It moves old particles from the active area of the queue
  231. /// to the retired section.
  232. /// </summary>
  233. void RetireActiveParticles ()
  234. {
  235. float particleDuration = (float)settings.Duration.TotalSeconds;
  236. while (firstActiveParticle != firstNewParticle) {
  237. // Is this particle old enough to retire?
  238. // We multiply the active particle index by four, because each
  239. // particle consists of a quad that is made up of four vertices.
  240. float particleAge = currentTime - particles [firstActiveParticle * 4].Time;
  241. if (particleAge < particleDuration)
  242. break;
  243. // Remember the time at which we retired this particle.
  244. particles [firstActiveParticle * 4].Time = drawCounter;
  245. // Move the particle from the active to the retired queue.
  246. firstActiveParticle++;
  247. if (firstActiveParticle >= settings.MaxParticles)
  248. firstActiveParticle = 0;
  249. }
  250. }
  251. /// <summary>
  252. /// Helper for checking when retired particles have been kept around long
  253. /// enough that we can be sure the GPU is no longer using them. It moves
  254. /// old particles from the retired area of the queue to the free section.
  255. /// </summary>
  256. void FreeRetiredParticles ()
  257. {
  258. while (firstRetiredParticle != firstActiveParticle) {
  259. // Has this particle been unused long enough that
  260. // the GPU is sure to be finished with it?
  261. // We multiply the retired particle index by four, because each
  262. // particle consists of a quad that is made up of four vertices.
  263. int age = drawCounter - (int)particles [firstRetiredParticle * 4].Time;
  264. // The GPU is never supposed to get more than 2 frames behind the CPU.
  265. // We add 1 to that, just to be safe in case of buggy drivers that
  266. // might bend the rules and let the GPU get further behind.
  267. if (age < 3)
  268. break;
  269. // Move the particle from the retired to the free queue.
  270. firstRetiredParticle++;
  271. if (firstRetiredParticle >= settings.MaxParticles)
  272. firstRetiredParticle = 0;
  273. }
  274. }
  275. /// <summary>
  276. /// Draws the particle system.
  277. /// </summary>
  278. public override void Draw (GameTime gameTime)
  279. {
  280. GraphicsDevice device = GraphicsDevice;
  281. // Restore the vertex buffer contents if the graphics device was lost.
  282. if (vertexBuffer.IsContentLost) {
  283. vertexBuffer.SetData (particles);
  284. }
  285. // If there are any particles waiting in the newly added queue,
  286. // we'd better upload them to the GPU ready for drawing.
  287. if (firstNewParticle != firstFreeParticle) {
  288. AddNewParticlesToVertexBuffer ();
  289. }
  290. // If there are any active particles, draw them now!
  291. if (firstActiveParticle != firstFreeParticle) {
  292. device.BlendState = settings.BlendState;
  293. device.DepthStencilState = DepthStencilState.DepthRead;
  294. // Set an effect parameter describing the viewport size. This is
  295. // needed to convert particle sizes into screen space point sizes.
  296. effectViewportScaleParameter.SetValue (new Vector2 (0.5f / device.Viewport.AspectRatio, -0.5f));
  297. // Set an effect parameter describing the current time. All the vertex
  298. // shader particle animation is keyed off this value.
  299. effectTimeParameter.SetValue (currentTime);
  300. // Set the particle vertex and index buffer.
  301. device.SetVertexBuffer (vertexBuffer);
  302. device.Indices = indexBuffer;
  303. // Activate the particle effect.
  304. foreach (EffectPass pass in particleEffect.CurrentTechnique.Passes) {
  305. pass.Apply ();
  306. if (firstActiveParticle < firstFreeParticle) {
  307. // If the active particles are all in one consecutive range,
  308. // we can draw them all in a single call.
  309. device.DrawIndexedPrimitives (PrimitiveType.TriangleList, 0,
  310. firstActiveParticle * 4, (firstFreeParticle - firstActiveParticle) * 4,
  311. firstActiveParticle * 6, (firstFreeParticle - firstActiveParticle) * 2);
  312. } else {
  313. // If the active particle range wraps past the end of the queue
  314. // back to the start, we must split them over two draw calls.
  315. device.DrawIndexedPrimitives (PrimitiveType.TriangleList, 0,
  316. firstActiveParticle * 4, (settings.MaxParticles - firstActiveParticle) * 4,
  317. firstActiveParticle * 6, (settings.MaxParticles - firstActiveParticle) * 2);
  318. if (firstFreeParticle > 0) {
  319. device.DrawIndexedPrimitives (PrimitiveType.TriangleList, 0,
  320. 0, firstFreeParticle * 4,
  321. 0, firstFreeParticle * 2);
  322. }
  323. }
  324. }
  325. // Reset some of the renderstates that we changed,
  326. // so as not to mess up any other subsequent drawing.
  327. device.DepthStencilState = DepthStencilState.Default;
  328. }
  329. drawCounter++;
  330. }
  331. /// <summary>
  332. /// Helper for uploading new particles from our managed
  333. /// array to the GPU vertex buffer.
  334. /// </summary>
  335. void AddNewParticlesToVertexBuffer ()
  336. {
  337. int stride = ParticleVertex.SizeInBytes;
  338. if (firstNewParticle < firstFreeParticle) {
  339. // If the new particles are all in one consecutive range,
  340. // we can upload them all in a single call.
  341. // vertexBuffer.SetData (firstNewParticle * stride * 4, particles,
  342. // firstNewParticle * 4,
  343. // (firstFreeParticle - firstNewParticle) * 4,
  344. // stride, SetDataOptions.NoOverwrite); } else {
  345. // If the new particle range wraps past the end of the queue
  346. // back to the start, we must split them over two upload calls.
  347. // vertexBuffer.SetData (firstNewParticle * stride * 4, particles,
  348. // firstNewParticle * 4,
  349. // (settings.MaxParticles - firstNewParticle) * 4,
  350. // stride, SetDataOptions.NoOverwrite);
  351. if (firstFreeParticle > 0) {
  352. // vertexBuffer.SetData (0, particles,
  353. // 0, firstFreeParticle * 4,
  354. // stride, SetDataOptions.NoOverwrite);
  355. }
  356. }
  357. // Move the particles we just uploaded from the new to the active queue.
  358. firstNewParticle = firstFreeParticle;
  359. }
  360. #endregion
  361. #region Public Methods
  362. /// <summary>
  363. /// Sets the camera view and projection matrices
  364. /// that will be used to draw this particle system.
  365. /// </summary>
  366. public void SetCamera (Matrix view, Matrix projection)
  367. {
  368. effectViewParameter.SetValue (view);
  369. effectProjectionParameter.SetValue (projection);
  370. }
  371. /// <summary>
  372. /// Adds a new particle to the system.
  373. /// </summary>
  374. public void AddParticle (Vector3 position, Vector3 velocity)
  375. {
  376. // Figure out where in the circular queue to allocate the new particle.
  377. int nextFreeParticle = firstFreeParticle + 1;
  378. if (nextFreeParticle >= settings.MaxParticles)
  379. nextFreeParticle = 0;
  380. // If there are no free particles, we just have to give up.
  381. if (nextFreeParticle == firstRetiredParticle)
  382. return;
  383. // Adjust the input velocity based on how much
  384. // this particle system wants to be affected by it.
  385. velocity *= settings.EmitterVelocitySensitivity;
  386. // Add in some random amount of horizontal velocity.
  387. float horizontalVelocity = MathHelper.Lerp (settings.MinHorizontalVelocity,
  388. settings.MaxHorizontalVelocity,
  389. (float)random.NextDouble ());
  390. double horizontalAngle = random.NextDouble () * MathHelper.TwoPi;
  391. velocity.X += horizontalVelocity * (float)Math.Cos (horizontalAngle);
  392. velocity.Z += horizontalVelocity * (float)Math.Sin (horizontalAngle);
  393. // Add in some random amount of vertical velocity.
  394. velocity.Y += MathHelper.Lerp (settings.MinVerticalVelocity,
  395. settings.MaxVerticalVelocity,
  396. (float)random.NextDouble ());
  397. // Choose four random control values. These will be used by the vertex
  398. // shader to give each particle a different size, rotation, and color.
  399. Color randomValues = new Color ((byte)random.Next (255),
  400. (byte)random.Next (255),
  401. (byte)random.Next (255),
  402. (byte)random.Next (255));
  403. // Fill in the particle vertex structure.
  404. for (int i = 0; i < 4; i++) {
  405. particles [firstFreeParticle * 4 + i].Position = position;
  406. particles [firstFreeParticle * 4 + i].Velocity = velocity;
  407. particles [firstFreeParticle * 4 + i].Random = randomValues;
  408. particles [firstFreeParticle * 4 + i].Time = currentTime;
  409. }
  410. firstFreeParticle = nextFreeParticle;
  411. }
  412. #endregion
  413. }
  414. }