ParticleSystem.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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. settings = content.Load<ParticleSettings>(settingsName);
  143. // Allocate the particle array, and fill in the corner fields (which never change).
  144. particles = new ParticleVertex[settings.MaxParticles * 4];
  145. for (int i = 0; i < settings.MaxParticles; i++)
  146. {
  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. {
  160. indices[i * 6 + 0] = (ushort)(i * 4 + 0);
  161. indices[i * 6 + 1] = (ushort)(i * 4 + 1);
  162. indices[i * 6 + 2] = (ushort)(i * 4 + 2);
  163. indices[i * 6 + 3] = (ushort)(i * 4 + 0);
  164. indices[i * 6 + 4] = (ushort)(i * 4 + 2);
  165. indices[i * 6 + 5] = (ushort)(i * 4 + 3);
  166. }
  167. indexBuffer = new IndexBuffer(GraphicsDevice, typeof(ushort), indices.Length, BufferUsage.WriteOnly);
  168. indexBuffer.SetData(indices);
  169. }
  170. /// <summary>
  171. /// Helper for loading and initializing the particle effect.
  172. /// </summary>
  173. void LoadParticleEffect()
  174. {
  175. Effect effect = content.Load<Effect>("ParticleEffect");
  176. // If we have several particle systems, the content manager will return
  177. // a single shared effect instance to them all. But we want to preconfigure
  178. // the effect with parameters that are specific to this particular
  179. // particle system. By cloning the effect, we prevent one particle system
  180. // from stomping over the parameter settings of another.
  181. particleEffect = effect.Clone();
  182. EffectParameterCollection parameters = particleEffect.Parameters;
  183. // Look up shortcuts for parameters that change every frame.
  184. effectViewParameter = parameters["View"];
  185. effectProjectionParameter = parameters["Projection"];
  186. effectViewportScaleParameter = parameters["ViewportScale"];
  187. effectTimeParameter = parameters["CurrentTime"];
  188. // Set the values of parameters that do not change.
  189. parameters["Duration"].SetValue((float)settings.Duration.TotalSeconds);
  190. parameters["DurationRandomness"].SetValue(settings.DurationRandomness);
  191. parameters["Gravity"].SetValue(settings.Gravity);
  192. parameters["EndVelocity"].SetValue(settings.EndVelocity);
  193. parameters["MinColor"].SetValue(settings.MinColor.ToVector4());
  194. parameters["MaxColor"].SetValue(settings.MaxColor.ToVector4());
  195. parameters["RotateSpeed"].SetValue(
  196. new Vector2(settings.MinRotateSpeed, settings.MaxRotateSpeed));
  197. parameters["StartSize"].SetValue(
  198. new Vector2(settings.MinStartSize, settings.MaxStartSize));
  199. parameters["EndSize"].SetValue(
  200. new Vector2(settings.MinEndSize, settings.MaxEndSize));
  201. // Load the particle texture, and set it onto the effect.
  202. Texture2D texture = content.Load<Texture2D>(settings.TextureName);
  203. parameters["Texture"].SetValue(texture);
  204. }
  205. #endregion
  206. #region Update and Draw
  207. /// <summary>
  208. /// Updates the particle system.
  209. /// </summary>
  210. public override void Update(GameTime gameTime)
  211. {
  212. if (gameTime == null)
  213. throw new ArgumentNullException("gameTime");
  214. currentTime += (float)gameTime.ElapsedGameTime.TotalSeconds;
  215. RetireActiveParticles();
  216. FreeRetiredParticles();
  217. // If we let our timer go on increasing for ever, it would eventually
  218. // run out of floating point precision, at which point the particles
  219. // would render incorrectly. An easy way to prevent this is to notice
  220. // that the time value doesn't matter when no particles are being drawn,
  221. // so we can reset it back to zero any time the active queue is empty.
  222. if (firstActiveParticle == firstFreeParticle)
  223. currentTime = 0;
  224. if (firstRetiredParticle == firstActiveParticle)
  225. drawCounter = 0;
  226. }
  227. /// <summary>
  228. /// Helper for checking when active particles have reached the end of
  229. /// their life. It moves old particles from the active area of the queue
  230. /// to the retired section.
  231. /// </summary>
  232. void RetireActiveParticles()
  233. {
  234. float particleDuration = (float)settings.Duration.TotalSeconds;
  235. while (firstActiveParticle != firstNewParticle)
  236. {
  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. {
  260. // Has this particle been unused long enough that
  261. // the GPU is sure to be finished with it?
  262. // We multiply the retired particle index by four, because each
  263. // particle consists of a quad that is made up of four vertices.
  264. int age = drawCounter - (int)particles[firstRetiredParticle * 4].Time;
  265. // The GPU is never supposed to get more than 2 frames behind the CPU.
  266. // We add 1 to that, just to be safe in case of buggy drivers that
  267. // might bend the rules and let the GPU get further behind.
  268. if (age < 3)
  269. break;
  270. // Move the particle from the retired to the free queue.
  271. firstRetiredParticle++;
  272. if (firstRetiredParticle >= settings.MaxParticles)
  273. firstRetiredParticle = 0;
  274. }
  275. }
  276. /// <summary>
  277. /// Draws the particle system.
  278. /// </summary>
  279. public override void Draw(GameTime gameTime)
  280. {
  281. GraphicsDevice device = GraphicsDevice;
  282. // Restore the vertex buffer contents if the graphics device was lost.
  283. if (vertexBuffer.IsContentLost)
  284. {
  285. vertexBuffer.SetData(particles);
  286. }
  287. // If there are any particles waiting in the newly added queue,
  288. // we'd better upload them to the GPU ready for drawing.
  289. if (firstNewParticle != firstFreeParticle)
  290. {
  291. AddNewParticlesToVertexBuffer();
  292. }
  293. // If there are any active particles, draw them now!
  294. if (firstActiveParticle != firstFreeParticle)
  295. {
  296. device.BlendState = settings.BlendState;
  297. device.DepthStencilState = DepthStencilState.DepthRead;
  298. // Set an effect parameter describing the viewport size. This is
  299. // needed to convert particle sizes into screen space point sizes.
  300. effectViewportScaleParameter.SetValue(new Vector2(0.5f / device.Viewport.AspectRatio, -0.5f));
  301. // Set an effect parameter describing the current time. All the vertex
  302. // shader particle animation is keyed off this value.
  303. effectTimeParameter.SetValue(currentTime);
  304. // Set the particle vertex and index buffer.
  305. device.SetVertexBuffer(vertexBuffer);
  306. device.Indices = indexBuffer;
  307. // Activate the particle effect.
  308. foreach (EffectPass pass in particleEffect.CurrentTechnique.Passes)
  309. {
  310. pass.Apply();
  311. if (firstActiveParticle < firstFreeParticle)
  312. {
  313. // If the active particles are all in one consecutive range,
  314. // we can draw them all in a single call.
  315. device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0,
  316. firstActiveParticle * 4, (firstFreeParticle - firstActiveParticle) * 4,
  317. firstActiveParticle * 6, (firstFreeParticle - firstActiveParticle) * 2);
  318. }
  319. else
  320. {
  321. // If the active particle range wraps past the end of the queue
  322. // back to the start, we must split them over two draw calls.
  323. device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0,
  324. firstActiveParticle * 4, (settings.MaxParticles - firstActiveParticle) * 4,
  325. firstActiveParticle * 6, (settings.MaxParticles - firstActiveParticle) * 2);
  326. if (firstFreeParticle > 0)
  327. {
  328. device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0,
  329. 0, firstFreeParticle * 4,
  330. 0, firstFreeParticle * 2);
  331. }
  332. }
  333. }
  334. // Reset some of the renderstates that we changed,
  335. // so as not to mess up any other subsequent drawing.
  336. device.DepthStencilState = DepthStencilState.Default;
  337. }
  338. drawCounter++;
  339. }
  340. /// <summary>
  341. /// Helper for uploading new particles from our managed
  342. /// array to the GPU vertex buffer.
  343. /// </summary>
  344. void AddNewParticlesToVertexBuffer()
  345. {
  346. int stride = ParticleVertex.SizeInBytes;
  347. if (firstNewParticle < firstFreeParticle)
  348. {
  349. // If the new particles are all in one consecutive range,
  350. // we can upload them all in a single call.
  351. vertexBuffer.SetData(firstNewParticle * stride * 4, particles,
  352. firstNewParticle * 4,
  353. (firstFreeParticle - firstNewParticle) * 4,
  354. stride, SetDataOptions.NoOverwrite);
  355. }
  356. else
  357. {
  358. // If the new particle range wraps past the end of the queue
  359. // back to the start, we must split them over two upload calls.
  360. vertexBuffer.SetData(firstNewParticle * stride * 4, particles,
  361. firstNewParticle * 4,
  362. (settings.MaxParticles - firstNewParticle) * 4,
  363. stride, SetDataOptions.NoOverwrite);
  364. if (firstFreeParticle > 0)
  365. {
  366. vertexBuffer.SetData(0, particles,
  367. 0, firstFreeParticle * 4,
  368. stride, SetDataOptions.NoOverwrite);
  369. }
  370. }
  371. // Move the particles we just uploaded from the new to the active queue.
  372. firstNewParticle = firstFreeParticle;
  373. }
  374. #endregion
  375. #region Public Methods
  376. /// <summary>
  377. /// Sets the camera view and projection matrices
  378. /// that will be used to draw this particle system.
  379. /// </summary>
  380. public void SetCamera(Matrix view, Matrix projection)
  381. {
  382. effectViewParameter.SetValue(view);
  383. effectProjectionParameter.SetValue(projection);
  384. }
  385. /// <summary>
  386. /// Adds a new particle to the system.
  387. /// </summary>
  388. public void AddParticle(Vector3 position, Vector3 velocity)
  389. {
  390. // Figure out where in the circular queue to allocate the new particle.
  391. int nextFreeParticle = firstFreeParticle + 1;
  392. if (nextFreeParticle >= settings.MaxParticles)
  393. nextFreeParticle = 0;
  394. // If there are no free particles, we just have to give up.
  395. if (nextFreeParticle == firstRetiredParticle)
  396. return;
  397. // Adjust the input velocity based on how much
  398. // this particle system wants to be affected by it.
  399. velocity *= settings.EmitterVelocitySensitivity;
  400. // Add in some random amount of horizontal velocity.
  401. float horizontalVelocity = MathHelper.Lerp(settings.MinHorizontalVelocity,
  402. settings.MaxHorizontalVelocity,
  403. (float)random.NextDouble());
  404. double horizontalAngle = random.NextDouble() * MathHelper.TwoPi;
  405. velocity.X += horizontalVelocity * (float)Math.Cos(horizontalAngle);
  406. velocity.Z += horizontalVelocity * (float)Math.Sin(horizontalAngle);
  407. // Add in some random amount of vertical velocity.
  408. velocity.Y += MathHelper.Lerp(settings.MinVerticalVelocity,
  409. settings.MaxVerticalVelocity,
  410. (float)random.NextDouble());
  411. // Choose four random control values. These will be used by the vertex
  412. // shader to give each particle a different size, rotation, and color.
  413. Color randomValues = new Color((byte)random.Next(255),
  414. (byte)random.Next(255),
  415. (byte)random.Next(255),
  416. (byte)random.Next(255));
  417. // Fill in the particle vertex structure.
  418. for (int i = 0; i < 4; i++)
  419. {
  420. particles[firstFreeParticle * 4 + i].Position = position;
  421. particles[firstFreeParticle * 4 + i].Velocity = velocity;
  422. particles[firstFreeParticle * 4 + i].Random = randomValues;
  423. particles[firstFreeParticle * 4 + i].Time = currentTime;
  424. }
  425. firstFreeParticle = nextFreeParticle;
  426. }
  427. #endregion
  428. }
  429. }