XMLParticleSystem.cs 22 KB

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