ParticleSystem.cs 23 KB

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