2
0

ParticleSystem.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. #region File Description
  2. //-----------------------------------------------------------------------------
  3. // SmokePlumeParticleSystem.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.Audio;
  15. using Microsoft.Xna.Framework.GamerServices;
  16. using Microsoft.Xna.Framework.Graphics;
  17. using Microsoft.Xna.Framework.Input;
  18. using Microsoft.Xna.Framework.Storage;
  19. using Microsoft.Xna.Framework.Content;
  20. using Microsoft.Xna.Framework.Media;
  21. #endregion
  22. namespace ParticleSample
  23. {
  24. /// <summary>
  25. /// ParticleSystem is an abstract class that provides the basic functionality to
  26. /// create a particle effect. Different subclasses will have different effects,
  27. /// such as fire, explosions, and plumes of smoke. To use these subclasses,
  28. /// simply call AddParticles, and pass in where the particles should exist
  29. /// </summary>
  30. public abstract class ParticleSystem : DrawableGameComponent
  31. {
  32. // these two values control the order that particle systems are drawn in.
  33. // typically, particles that use additive blending should be drawn on top of
  34. // particles that use regular alpha blending. ParticleSystems should therefore
  35. // set their DrawOrder to the appropriate value in InitializeConstants, though
  36. // it is possible to use other values for more advanced effects.
  37. public const int AlphaBlendDrawOrder = 100;
  38. public const int AdditiveDrawOrder = 200;
  39. // a reference to the main game; we'll keep this around because it exposes a
  40. // content manager and a sprite batch for us to use.
  41. private ParticleSampleGame game;
  42. // the texture this particle system will use.
  43. private Texture2D texture;
  44. // the origin when we're drawing textures. this will be the middle of the
  45. // texture.
  46. private Vector2 origin;
  47. // this number represents the maximum number of effects this particle system
  48. // will be expected to draw at one time. this is set in the constructor and is
  49. // used to calculate how many particles we will need.
  50. private int howManyEffects;
  51. // the array of particles used by this system. these are reused, so that calling
  52. // AddParticles will not cause any allocations.
  53. Particle[] particles;
  54. // the queue of free particles keeps track of particles that are not curently
  55. // being used by an effect. when a new effect is requested, particles are taken
  56. // from this queue. when particles are finished they are put onto this queue.
  57. Queue<Particle> freeParticles;
  58. /// <summary>
  59. /// returns the number of particles that are available for a new effect.
  60. /// </summary>
  61. public int FreeParticleCount
  62. {
  63. get
  64. {
  65. if (freeParticles != null )
  66. {
  67. return freeParticles.Count;
  68. }
  69. else
  70. {
  71. return 0;
  72. }
  73. }
  74. }
  75. // This region of values control the "look" of the particle system, and should
  76. // be set by deriving particle systems in the InitializeConstants method. The
  77. // values are then used by the virtual function InitializeParticle. Subclasses
  78. // can override InitializeParticle for further
  79. // customization.
  80. #region constants to be set by subclasses
  81. /// <summary>
  82. /// minNumParticles and maxNumParticles control the number of particles that are
  83. /// added when AddParticles is called. The number of particles will be a random
  84. /// number between minNumParticles and maxNumParticles.
  85. /// </summary>
  86. protected int minNumParticles;
  87. protected int maxNumParticles;
  88. /// <summary>
  89. /// this controls the texture that the particle system uses. It will be used as
  90. /// an argument to ContentManager.Load.
  91. /// </summary>
  92. protected string textureFilename;
  93. /// <summary>
  94. /// minInitialSpeed and maxInitialSpeed are used to control the initial velocity
  95. /// of the particles. The particle's initial speed will be a random number
  96. /// between these two. The direction is determined by the function
  97. /// PickRandomDirection, which can be overriden.
  98. /// </summary>
  99. protected float minInitialSpeed;
  100. protected float maxInitialSpeed;
  101. /// <summary>
  102. /// minAcceleration and maxAcceleration are used to control the acceleration of
  103. /// the particles. The particle's acceleration will be a random number between
  104. /// these two. By default, the direction of acceleration is the same as the
  105. /// direction of the initial velocity.
  106. /// </summary>
  107. protected float minAcceleration;
  108. protected float maxAcceleration;
  109. /// <summary>
  110. /// minRotationSpeed and maxRotationSpeed control the particles' angular
  111. /// velocity: the speed at which particles will rotate. Each particle's rotation
  112. /// speed will be a random number between minRotationSpeed and maxRotationSpeed.
  113. /// Use smaller numbers to make particle systems look calm and wispy, and large
  114. /// numbers for more violent effects.
  115. /// </summary>
  116. protected float minRotationSpeed;
  117. protected float maxRotationSpeed;
  118. /// <summary>
  119. /// minLifetime and maxLifetime are used to control the lifetime. Each
  120. /// particle's lifetime will be a random number between these two. Lifetime
  121. /// is used to determine how long a particle "lasts." Also, in the base
  122. /// implementation of Draw, lifetime is also used to calculate alpha and scale
  123. /// values to avoid particles suddenly "popping" into view
  124. /// </summary>
  125. protected float minLifetime;
  126. protected float maxLifetime;
  127. /// <summary>
  128. /// to get some additional variance in the appearance of the particles, we give
  129. /// them all random scales. the scale is a value between minScale and maxScale,
  130. /// and is additionally affected by the particle's lifetime to avoid particles
  131. /// "popping" into view.
  132. /// </summary>
  133. protected float minScale;
  134. protected float maxScale;
  135. /// <summary>
  136. /// different effects can use different blend modes. fire and explosions work
  137. /// well with additive blending, for example.
  138. /// </summary>
  139. protected BlendState spriteBlendMode;
  140. #endregion
  141. /// <summary>
  142. /// Constructs a new ParticleSystem.
  143. /// </summary>
  144. /// <param name="game">The host for this particle system. The game keeps the
  145. /// content manager and sprite batch for us.</param>
  146. /// <param name="howManyEffects">the maximum number of particle effects that
  147. /// are expected on screen at once.</param>
  148. /// <remarks>it is tempting to set the value of howManyEffects very high.
  149. /// However, this value should be set to the minimum possible, because
  150. /// it has a large impact on the amount of memory required, and slows down the
  151. /// Update and Draw functions.</remarks>
  152. protected ParticleSystem(ParticleSampleGame game, int howManyEffects)
  153. : base(game)
  154. {
  155. this.game = game;
  156. this.howManyEffects = howManyEffects;
  157. }
  158. /// <summary>
  159. /// override the base class's Initialize to do some additional work; we want to
  160. /// call InitializeConstants to let subclasses set the constants that we'll use.
  161. ///
  162. /// also, the particle array and freeParticles queue are set up here.
  163. /// </summary>
  164. public override void Initialize()
  165. {
  166. InitializeConstants();
  167. // calculate the total number of particles we will ever need, using the
  168. // max number of effects and the max number of particles per effect.
  169. // once these particles are allocated, they will be reused, so that
  170. // we don't put any pressure on the garbage collector.
  171. particles = new Particle[howManyEffects * maxNumParticles];
  172. freeParticles = new Queue<Particle>(howManyEffects * maxNumParticles);
  173. for (int i = 0; i < particles.Length; i++)
  174. {
  175. particles[i] = new Particle();
  176. freeParticles.Enqueue(particles[i]);
  177. }
  178. base.Initialize();
  179. }
  180. /// <summary>
  181. /// this abstract function must be overriden by subclasses of ParticleSystem.
  182. /// It's here that they should set all the constants marked in the region
  183. /// "constants to be set by subclasses", which give each ParticleSystem its
  184. /// specific flavor.
  185. /// </summary>
  186. protected abstract void InitializeConstants();
  187. /// <summary>
  188. /// Override the base class LoadContent to load the texture. once it's
  189. /// loaded, calculate the origin.
  190. /// </summary>
  191. protected override void LoadContent()
  192. {
  193. // make sure sub classes properly set textureFilename.
  194. if (string.IsNullOrEmpty(textureFilename))
  195. {
  196. string message = "textureFilename wasn't set properly, so the " +
  197. "particle system doesn't know what texture to load. Make " +
  198. "sure your particle system's InitializeConstants function " +
  199. "properly sets textureFilename.";
  200. throw new InvalidOperationException(message);
  201. }
  202. // load the texture....
  203. texture = game.Content.Load<Texture2D>(textureFilename);
  204. // ... and calculate the center. this'll be used in the draw call, we
  205. // always want to rotate and scale around this point.
  206. origin.X = texture.Width / 2;
  207. origin.Y = texture.Height / 2;
  208. base.LoadContent();
  209. }
  210. /// <summary>
  211. /// AddParticles's job is to add an effect somewhere on the screen. If there
  212. /// aren't enough particles in the freeParticles queue, it will use as many as
  213. /// it can. This means that if there not enough particles available, calling
  214. /// AddParticles will have no effect.
  215. /// </summary>
  216. /// <param name="where">where the particle effect should be created</param>
  217. public void AddParticles(Vector2 where)
  218. {
  219. // the number of particles we want for this effect is a random number
  220. // somewhere between the two constants specified by the subclasses.
  221. int numParticles =
  222. ParticleSampleGame.Random.Next(minNumParticles, maxNumParticles);
  223. // create that many particles, if you can.
  224. for (int i = 0; i < numParticles && freeParticles.Count > 0; i++)
  225. {
  226. // grab a particle from the freeParticles queue, and Initialize it.
  227. Particle p = freeParticles.Dequeue();
  228. InitializeParticle(p, where);
  229. }
  230. }
  231. /// <summary>
  232. /// InitializeParticle randomizes some properties for a particle, then
  233. /// calls initialize on it. It can be overriden by subclasses if they
  234. /// want to modify the way particles are created. For example,
  235. /// SmokePlumeParticleSystem overrides this function make all particles
  236. /// accelerate to the right, simulating wind.
  237. /// </summary>
  238. /// <param name="p">the particle to initialize</param>
  239. /// <param name="where">the position on the screen that the particle should be
  240. /// </param>
  241. protected virtual void InitializeParticle(Particle p, Vector2 where)
  242. {
  243. // first, call PickRandomDirection to figure out which way the particle
  244. // will be moving. velocity and acceleration's values will come from this.
  245. Vector2 direction = PickRandomDirection();
  246. // pick some random values for our particle
  247. float velocity =
  248. ParticleSampleGame.RandomBetween(minInitialSpeed, maxInitialSpeed);
  249. float acceleration =
  250. ParticleSampleGame.RandomBetween(minAcceleration, maxAcceleration);
  251. float lifetime =
  252. ParticleSampleGame.RandomBetween(minLifetime, maxLifetime);
  253. float scale =
  254. ParticleSampleGame.RandomBetween(minScale, maxScale);
  255. float rotationSpeed =
  256. ParticleSampleGame.RandomBetween(minRotationSpeed, maxRotationSpeed);
  257. // then initialize it with those random values. initialize will save those,
  258. // and make sure it is marked as active.
  259. p.Initialize(
  260. where, velocity * direction, acceleration * direction,
  261. lifetime, scale, rotationSpeed);
  262. }
  263. /// <summary>
  264. /// PickRandomDirection is used by InitializeParticles to decide which direction
  265. /// particles will move. The default implementation is a random vector in a
  266. /// circular pattern.
  267. /// </summary>
  268. protected virtual Vector2 PickRandomDirection()
  269. {
  270. float angle = ParticleSampleGame.RandomBetween(0, MathHelper.TwoPi);
  271. return new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle));
  272. }
  273. /// <summary>
  274. /// overriden from DrawableGameComponent, Update will update all of the active
  275. /// particles.
  276. /// </summary>
  277. public override void Update(GameTime gameTime)
  278. {
  279. // calculate dt, the change in the since the last frame. the particle
  280. // updates will use this value.
  281. float dt = (float)gameTime.ElapsedGameTime.TotalSeconds;
  282. // go through all of the particles...
  283. foreach (Particle p in particles)
  284. {
  285. if (p.Active)
  286. {
  287. // ... and if they're active, update them.
  288. p.Update(dt);
  289. // if that update finishes them, put them onto the free particles
  290. // queue.
  291. if (!p.Active)
  292. {
  293. freeParticles.Enqueue(p);
  294. }
  295. }
  296. }
  297. base.Update(gameTime);
  298. }
  299. /// <summary>
  300. /// overriden from DrawableGameComponent, Draw will use ParticleSampleGame's
  301. /// sprite batch to render all of the active particles.
  302. /// </summary>
  303. public override void Draw(GameTime gameTime)
  304. {
  305. // tell sprite batch to begin, using the spriteBlendMode specified in
  306. // initializeConstants
  307. game.SpriteBatch.Begin(SpriteSortMode.Deferred, spriteBlendMode);
  308. foreach (Particle p in particles)
  309. {
  310. // skip inactive particles
  311. if (!p.Active)
  312. continue;
  313. // normalized lifetime is a value from 0 to 1 and represents how far
  314. // a particle is through its life. 0 means it just started, .5 is half
  315. // way through, and 1.0 means it's just about to be finished.
  316. // this value will be used to calculate alpha and scale, to avoid
  317. // having particles suddenly appear or disappear.
  318. float normalizedLifetime = p.TimeSinceStart / p.Lifetime;
  319. // we want particles to fade in and fade out, so we'll calculate alpha
  320. // to be (normalizedLifetime) * (1-normalizedLifetime). this way, when
  321. // normalizedLifetime is 0 or 1, alpha is 0. the maximum value is at
  322. // normalizedLifetime = .5, and is
  323. // (normalizedLifetime) * (1-normalizedLifetime)
  324. // (.5) * (1-.5)
  325. // .25
  326. // since we want the maximum alpha to be 1, not .25, we'll scale the
  327. // entire equation by 4.
  328. float alpha = 4 * normalizedLifetime * (1 - normalizedLifetime);
  329. Color color = new Color(new Vector4(1, 1, 1, alpha));
  330. // make particles grow as they age. they'll start at 75% of their size,
  331. // and increase to 100% once they're finished.
  332. float scale = p.Scale * (.75f + .25f * normalizedLifetime);
  333. game.SpriteBatch.Draw(texture, p.Position, null, color,
  334. p.Rotation, origin, scale, SpriteEffects.None, 0.0f);
  335. }
  336. game.SpriteBatch.End();
  337. base.Draw(gameTime);
  338. }
  339. }
  340. }