ParticleEffect.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. // Copyright (c) Craftwork Games. All rights reserved.
  2. // Licensed under the MIT license.
  3. // See LICENSE file in the project root for full license information.
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using Microsoft.Xna.Framework;
  9. using Microsoft.Xna.Framework.Content;
  10. using MonoGame.Extended.Particles.Primitives;
  11. namespace MonoGame.Extended.Particles;
  12. /// <summary>
  13. /// Represents a complete particle effect composed of multiple emitters.
  14. /// </summary>
  15. /// <remarks>
  16. /// The <see cref="ParticleEffect"/> class serves as a container for one or more <see cref="ParticleEmitter"/> instances,
  17. /// allowing for complex visual effects that combine different types of particle behaviors and appearances.
  18. ///
  19. /// Effects can be positioned, rotated, and scaled as a single unit, with all contained emitters being affected
  20. /// by these transformations. Effects also provide methods for triggering all emitters simultaneously.
  21. /// </remarks>
  22. public class ParticleEffect : IDisposable
  23. {
  24. private float _nextAutoTrigger;
  25. /// <summary>
  26. /// Gets or sets the name of this effect, used for identification and debugging.
  27. /// </summary>
  28. public string Name { get; set; }
  29. /// <summary>
  30. /// Gets or sets the position of this effect in 2D space.
  31. /// </summary>
  32. /// <remarks>
  33. /// This position is used as the reference point for all emitters in the effect.
  34. /// When the effect is updated, this position is passed to each emitter's update method.
  35. /// </remarks>
  36. public Vector2 Position { get; set; }
  37. /// <summary>
  38. /// Gets or sets the rotation of this effect, in radians.
  39. /// </summary>
  40. /// <remarks>
  41. /// This property can be used to rotate the entire effect around its position.
  42. /// Note that rotation is not automatically applied to emitters and must be handled by the rendering system.
  43. /// </remarks>
  44. public float Rotation { get; set; }
  45. /// <summary>
  46. /// Gets or sets the scale factor of this effect.
  47. /// </summary>
  48. /// <remarks>
  49. /// This property can be used to uniformly or non-uniformly scale the entire effect.
  50. /// Note that scaling is not automatically applied to emitters and must be handled by the rendering system.
  51. /// </remarks>
  52. public Vector2 Scale { get; set; }
  53. /// <summary>
  54. /// Gets or sets a value indicating whether this particle effect should automatically trigger its particle emitters.
  55. /// </summary>
  56. /// <remarks>
  57. /// When <see langword="true"/>, all emitters of this <see cref="ParticleEffect"/> will be triggered at the same
  58. /// based on the <see cref="AutoTriggerFrequency"/>. When <see langword="false"/>, users will need to manually call
  59. /// the <see cref="Trigger()"/> method to trigger emitters.
  60. /// </remarks>
  61. public bool AutoTrigger { get; set; }
  62. /// <summary>
  63. /// Gets or sets the frequency, in seconds, at which this <see cref="ParticleEffect"/> automatically triggers emitters.
  64. /// </summary>
  65. /// <remarks>
  66. /// If <see cref="AutoTrigger"/> is <see langword="false"/>, this value is ignored.
  67. /// </remarks>
  68. public float AutoTriggerFrequency { get; set; }
  69. /// <summary>
  70. /// Gets or sets the collection of emitters that compose this effect.
  71. /// </summary>
  72. /// <remarks>
  73. /// Each emitter in this collection contributes to the overall visual appearance of the effect,
  74. /// potentially with different behaviors, textures, and particle properties.
  75. /// </remarks>
  76. public List<ParticleEmitter> Emitters { get; set; }
  77. /// <summary>
  78. /// Gets a value indicating whether this <see cref="ParticleEffect"/> has been disposed.
  79. /// </summary>
  80. /// <value><see langword="true"/> if the effect has been disposed; otherwise, <see langword="false"/>.</value>
  81. public bool IsDisposed { get; private set; }
  82. /// <summary>
  83. /// Gets the total number of active particles across all emitters in this effect.
  84. /// </summary>
  85. /// <value>The sum of <see cref="ParticleEmitter.ActiveParticles"/> for all emitters in the effect.</value>
  86. public int ActiveParticles
  87. {
  88. get
  89. {
  90. return Emitters.Sum(t => t.ActiveParticles);
  91. }
  92. }
  93. /// <summary>
  94. /// Initializes a new instance of the <see cref="ParticleEffect"/> class with the specified name.
  95. /// </summary>
  96. /// <param name="name">The name of the effect, used for identification and debugging.</param>
  97. /// <remarks>
  98. /// This constructor initializes the effect with default position, rotation, and scale,
  99. /// and creates an empty collection of emitters.
  100. /// </remarks>
  101. public ParticleEffect(string name)
  102. {
  103. Name = name;
  104. Position = Vector2.Zero;
  105. Rotation = 0.0f;
  106. Scale = Vector2.One;
  107. Emitters = new List<ParticleEmitter>();
  108. AutoTrigger = true;
  109. AutoTriggerFrequency = 1.0f;
  110. }
  111. /// <summary>
  112. /// Finalizes an instance of the <see cref="ParticleEffect"/> class.
  113. /// </summary>
  114. ~ParticleEffect()
  115. {
  116. Dispose(false);
  117. }
  118. /// <summary>
  119. /// Advances the effect's state rapidly to simulate it having been active for a period of time.
  120. /// </summary>
  121. /// <param name="position">The position at which to simulate the effect.</param>
  122. /// <param name="seconds">The total time, in seconds, to simulate.</param>
  123. /// <param name="triggerPeriod">The time interval, in seconds, between simulated triggers.</param>
  124. /// <remarks>
  125. /// This method is useful for pre-filling a scene with particles that appear to have been emitted
  126. /// over time, rather than starting with an empty effect.
  127. /// </remarks>
  128. public void FastForward(Vector2 position, float seconds, float triggerPeriod)
  129. {
  130. float time = 0.0f;
  131. while (time < seconds)
  132. {
  133. Update(triggerPeriod);
  134. Trigger(position);
  135. time += triggerPeriod;
  136. }
  137. }
  138. /// <summary>
  139. /// Updates the state of all emitters in this effect.
  140. /// </summary>
  141. /// <param name="gameTime">The timing values for the current update cycle.</param>
  142. /// <exception cref="ObjectDisposedException">
  143. /// Thrown if this method is called after the effect has been disposed.
  144. /// </exception>
  145. public void Update(GameTime gameTime)
  146. {
  147. Update((float)gameTime.ElapsedGameTime.TotalSeconds);
  148. }
  149. /// <summary>
  150. /// Updates the state of all emitters in this effect.
  151. /// </summary>
  152. /// <param name="elapsedSeconds">The elapsed time, in seconds, since the last update.</param>
  153. /// <exception cref="ObjectDisposedException">
  154. /// Thrown if this method is called after the effect has been disposed.
  155. /// </exception>
  156. public void Update(float elapsedSeconds)
  157. {
  158. ObjectDisposedException.ThrowIf(IsDisposed, typeof(ParticleBuffer));
  159. if (AutoTrigger)
  160. {
  161. _nextAutoTrigger -= elapsedSeconds;
  162. if (_nextAutoTrigger <= 0)
  163. {
  164. Trigger();
  165. _nextAutoTrigger += AutoTriggerFrequency;
  166. }
  167. }
  168. for (int i = 0; i < Emitters.Count; i++)
  169. {
  170. Emitters[i].Update(elapsedSeconds, Position);
  171. }
  172. }
  173. /// <summary>
  174. /// Triggers all emitters in this effect at the effect's current position.
  175. /// </summary>
  176. public void Trigger()
  177. {
  178. Trigger(Position);
  179. }
  180. /// <summary>
  181. /// Triggers all emitters in this effect at the specified position.
  182. /// </summary>
  183. /// <param name="position">The position in 2D space at which to trigger the emitters.</param>
  184. /// <param name="layerDepth">The layer depth at which to render the emitted particles.</param>
  185. /// <exception cref="ObjectDisposedException">
  186. /// Thrown if this method is called after the effect has been disposed.
  187. /// </exception>
  188. public void Trigger(Vector2 position, float layerDepth = 0)
  189. {
  190. ObjectDisposedException.ThrowIf(IsDisposed, typeof(ParticleBuffer));
  191. for (int i = 0; i < Emitters.Count; i++)
  192. {
  193. Emitters[i].Trigger(position, layerDepth);
  194. }
  195. }
  196. /// <summary>
  197. /// Triggers all emitters in this effect along a line segment.
  198. /// </summary>
  199. /// <param name="line">The line segment along which to distribute triggered particles.</param>
  200. /// <param name="layerDepth">The layer depth at which to render the emitted particles.</param>
  201. /// <exception cref="ObjectDisposedException">
  202. /// Thrown if this method is called after the effect has been disposed.
  203. /// </exception>
  204. public void Trigger(LineSegment line, float layerDepth)
  205. {
  206. ObjectDisposedException.ThrowIf(IsDisposed, typeof(ParticleBuffer));
  207. for (int i = 0; i < Emitters.Count; i++)
  208. {
  209. Emitters[i].Trigger(line, layerDepth);
  210. }
  211. }
  212. /// <summary>
  213. /// Creates a new instance of the <see cref="ParticleEffect"/> class from a file.
  214. /// </summary>
  215. /// <param name="path">The path to the file containing the serialized effect data.</param>
  216. /// <param name="content">The content manager used to load graphical assets.</param>
  217. /// <returns>A new <see cref="ParticleEffect"/> instance with properties and emitters as defined in the file.</returns>
  218. /// <exception cref="ArgumentNullException"><paramref name="content"/> is <see langword="null"/></exception>
  219. /// <exception cref="ArgumentException"><paramref name="path"/> is <see langword="null"/> or empty.</exception>
  220. public static ParticleEffect FromFile(string path, ContentManager content)
  221. {
  222. return ParticleEffectSerializer.Deserialize(path, content);
  223. }
  224. /// <summary>
  225. /// Creates a new instance of the <see cref="ParticleEffect"/> class from a stream.
  226. /// </summary>
  227. /// <param name="stream">The stream to read from.</param>
  228. /// <param name="content">The <see cref="ContentManager"/> to use for loading textures.</param>
  229. /// <param name="baseDirectory">The base directory to use for resolving relative texture paths. If null, uses the ContentManager's RootDirectory.</param>
  230. /// <returns>A new <see cref="ParticleEffect"/> instance with properties and emitters as defined in the stream.</returns>
  231. /// <exception cref="ArgumentNullException"><paramref name="stream"/> or <paramref name="content"/> is <see langword="null"/></exception>
  232. public static ParticleEffect FromStream(Stream stream, ContentManager content, string baseDirectory)
  233. {
  234. return ParticleEffectSerializer.Deserialize(stream, content, baseDirectory);
  235. }
  236. /// <summary>
  237. /// Releases all resources used by the <see cref="ParticleEffect"/>.
  238. /// </summary>
  239. public void Dispose()
  240. {
  241. Dispose(true);
  242. GC.SuppressFinalize(this);
  243. }
  244. /// <summary>
  245. /// Releases the resources used by the <see cref="ParticleEffect"/>.
  246. /// </summary>
  247. /// <param name="disposing"><see langword="true"/> to release both managed and unmanaged resources;
  248. /// <see langword="false"/> to release only unmanaged resources.</param>
  249. private void Dispose(bool disposing)
  250. {
  251. if (IsDisposed) { return; }
  252. if (disposing)
  253. {
  254. for (int i = 0; i < Emitters.Count; i++)
  255. {
  256. Emitters[i].Dispose();
  257. }
  258. }
  259. IsDisposed = true;
  260. }
  261. /// <summary>
  262. /// Returns a string that represents the current effect.
  263. /// </summary>
  264. /// <returns>The <see cref="Name"/> of this effect.</returns>
  265. public override string ToString()
  266. {
  267. return Name;
  268. }
  269. }