Game.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. #region File Description
  2. //-----------------------------------------------------------------------------
  3. // Game.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 Microsoft.Xna.Framework;
  13. using Microsoft.Xna.Framework.Content;
  14. using Microsoft.Xna.Framework.Graphics;
  15. using Microsoft.Xna.Framework.Input;
  16. #endregion
  17. namespace Particle3DSample
  18. {
  19. /// <summary>
  20. /// Sample showing how to implement a particle system entirely
  21. /// on the GPU, using the vertex shader to animate particles.
  22. /// </summary>
  23. public class Particle3DSampleGame : Microsoft.Xna.Framework.Game
  24. {
  25. #region Fields
  26. GraphicsDeviceManager graphics;
  27. SpriteBatch spriteBatch;
  28. SpriteFont font;
  29. //Model grid;
  30. // This sample uses five different particle systems.
  31. ParticleSystem explosionParticles;
  32. ParticleSystem explosionSmokeParticles;
  33. ParticleSystem projectileTrailParticles;
  34. ParticleSystem smokePlumeParticles;
  35. ParticleSystem fireParticles;
  36. // The sample can switch between three different visual effects.
  37. enum ParticleState
  38. {
  39. Explosions,
  40. SmokePlume,
  41. RingOfFire,
  42. };
  43. ParticleState currentState = ParticleState.Explosions;
  44. // The explosions effect works by firing projectiles up into the
  45. // air, so we need to keep track of all the active projectiles.
  46. List<Projectile> projectiles = new List<Projectile> ();
  47. TimeSpan timeToNextProjectile = TimeSpan.Zero;
  48. // Random number generator for the fire effect.
  49. Random random = new Random ();
  50. // Input state.
  51. KeyboardState currentKeyboardState;
  52. GamePadState currentGamePadState;
  53. KeyboardState lastKeyboardState;
  54. GamePadState lastGamePadState;
  55. // Camera state.
  56. float cameraArc = -5;
  57. float cameraRotation = 0;
  58. float cameraDistance = 200;
  59. #endregion
  60. #region Initialization
  61. /// <summary>
  62. /// Constructor.
  63. /// </summary>
  64. public Particle3DSampleGame ()
  65. {
  66. graphics = new GraphicsDeviceManager (this);
  67. Content.RootDirectory = "Content";
  68. // Construct our particle system components.
  69. explosionParticles = new ParticleSystem (this, Content, "ExplosionSettings");
  70. explosionSmokeParticles = new ParticleSystem (this, Content, "ExplosionSmokeSettings");
  71. projectileTrailParticles = new ParticleSystem (this, Content, "ProjectileTrailSettings");
  72. smokePlumeParticles = new ParticleSystem (this, Content, "SmokePlumeSettings");
  73. fireParticles = new ParticleSystem (this, Content, "FireSettings");
  74. // Set the draw order so the explosions and fire
  75. // will appear over the top of the smoke.
  76. smokePlumeParticles.DrawOrder = 100;
  77. explosionSmokeParticles.DrawOrder = 200;
  78. projectileTrailParticles.DrawOrder = 300;
  79. explosionParticles.DrawOrder = 400;
  80. fireParticles.DrawOrder = 500;
  81. // Register the particle system components.
  82. Components.Add (explosionParticles);
  83. Components.Add (explosionSmokeParticles);
  84. Components.Add (projectileTrailParticles);
  85. Components.Add (smokePlumeParticles);
  86. Components.Add (fireParticles);
  87. }
  88. /// <summary>
  89. /// Load your graphics content.
  90. /// </summary>
  91. protected override void LoadContent ()
  92. {
  93. spriteBatch = new SpriteBatch (graphics.GraphicsDevice);
  94. //font = Content.Load<SpriteFont> ("Arial");
  95. font = Content.Load<SpriteFont> ("font");
  96. //grid = Content.Load<Model> ("grid");
  97. }
  98. #endregion
  99. #region Update and Draw
  100. /// <summary>
  101. /// Allows the game to run logic.
  102. /// </summary>
  103. protected override void Update (GameTime gameTime)
  104. {
  105. HandleInput ();
  106. UpdateCamera (gameTime);
  107. switch (currentState) {
  108. case ParticleState.Explosions:
  109. UpdateExplosions (gameTime);
  110. break;
  111. case ParticleState.SmokePlume:
  112. UpdateSmokePlume ();
  113. break;
  114. case ParticleState.RingOfFire:
  115. UpdateFire ();
  116. break;
  117. }
  118. UpdateProjectiles (gameTime);
  119. base.Update (gameTime);
  120. }
  121. /// <summary>
  122. /// Helper for updating the explosions effect.
  123. /// </summary>
  124. void UpdateExplosions (GameTime gameTime)
  125. {
  126. timeToNextProjectile -= gameTime.ElapsedGameTime;
  127. if (timeToNextProjectile <= TimeSpan.Zero) {
  128. // Create a new projectile once per second. The real work of moving
  129. // and creating particles is handled inside the Projectile class.
  130. projectiles.Add (new Projectile (explosionParticles,
  131. explosionSmokeParticles,
  132. projectileTrailParticles));
  133. timeToNextProjectile += TimeSpan.FromSeconds (1);
  134. }
  135. }
  136. /// <summary>
  137. /// Helper for updating the list of active projectiles.
  138. /// </summary>
  139. void UpdateProjectiles (GameTime gameTime)
  140. {
  141. int i = 0;
  142. while (i < projectiles.Count) {
  143. if (!projectiles [i].Update (gameTime)) {
  144. // Remove projectiles at the end of their life.
  145. projectiles.RemoveAt (i);
  146. } else {
  147. // Advance to the next projectile.
  148. i++;
  149. }
  150. }
  151. }
  152. /// <summary>
  153. /// Helper for updating the smoke plume effect.
  154. /// </summary>
  155. void UpdateSmokePlume ()
  156. {
  157. // This is trivial: we just create one new smoke particle per frame.
  158. smokePlumeParticles.AddParticle (Vector3.Zero, Vector3.Zero);
  159. }
  160. /// <summary>
  161. /// Helper for updating the fire effect.
  162. /// </summary>
  163. void UpdateFire ()
  164. {
  165. const
  166. int fireParticlesPerFrame = 20 ;
  167. // Create a number of fire particles, randomly positioned around a circle.
  168. for (int i = 0; i < fireParticlesPerFrame; i++) {
  169. fireParticles.AddParticle (RandomPointOnCircle (), Vector3.Zero);
  170. }
  171. // Create one smoke particle per frmae, too.
  172. smokePlumeParticles.AddParticle (RandomPointOnCircle (), Vector3.Zero);
  173. }
  174. /// <summary>
  175. /// Helper used by the UpdateFire method. Chooses a random location
  176. /// around a circle, at which a fire particle will be created.
  177. /// </summary>
  178. Vector3 RandomPointOnCircle ()
  179. {
  180. const
  181. float radius = 30 ;
  182. const
  183. float height = 40 ;
  184. double angle = random.NextDouble () * Math.PI * 2;
  185. float x = (float)Math.Cos (angle);
  186. float y = (float)Math.Sin (angle);
  187. return new Vector3 (x * radius, y * radius + height, 0);
  188. }
  189. /// <summary>
  190. /// This is called when the game should draw itself.
  191. /// </summary>
  192. protected override void Draw (GameTime gameTime)
  193. {
  194. GraphicsDevice device = graphics.GraphicsDevice;
  195. device.Clear (Color.CornflowerBlue);
  196. // Compute camera matrices.
  197. float aspectRatio = (float)device.Viewport.Width /
  198. (float)device.Viewport.Height;
  199. Matrix view = Matrix.CreateTranslation (0, -25, 0) *
  200. Matrix.CreateRotationY (MathHelper.ToRadians (cameraRotation)) *
  201. Matrix.CreateRotationX (MathHelper.ToRadians (cameraArc)) *
  202. Matrix.CreateLookAt (new Vector3 (0, 0, -cameraDistance),
  203. new Vector3 (0, 0, 0), Vector3.Up);
  204. Matrix projection = Matrix.CreatePerspectiveFieldOfView (MathHelper.PiOver4,
  205. aspectRatio,
  206. 1, 10000);
  207. // Pass camera matrices through to the particle system components.
  208. explosionParticles.SetCamera (view, projection);
  209. explosionSmokeParticles.SetCamera (view, projection);
  210. projectileTrailParticles.SetCamera (view, projection);
  211. smokePlumeParticles.SetCamera (view, projection);
  212. fireParticles.SetCamera (view, projection);
  213. // Draw our background grid and message text.
  214. DrawGrid (view, projection);
  215. DrawMessage ();
  216. // This will draw the particle system components.
  217. base.Draw (gameTime);
  218. }
  219. /// <summary>
  220. /// Helper for drawing the background grid model.
  221. /// </summary>
  222. void DrawGrid (Matrix view, Matrix projection)
  223. {
  224. GraphicsDevice device = graphics.GraphicsDevice;
  225. device.BlendState = BlendState.Opaque;
  226. device.DepthStencilState = DepthStencilState.Default;
  227. device.SamplerStates [0] = SamplerState.LinearWrap;
  228. //grid.Draw (Matrix.Identity, view, projection);
  229. }
  230. /// <summary>
  231. /// Helper for drawing our message text.
  232. /// </summary>
  233. void DrawMessage ()
  234. {
  235. string message = string.Format ("Current effect: {0}!!!\n" +
  236. "Hit the A button or space bar to switch.",
  237. currentState);
  238. spriteBatch.Begin ();
  239. spriteBatch.DrawString (font, message, new Vector2 (50, 50), Color.White);
  240. spriteBatch.End ();
  241. }
  242. #endregion
  243. #region Handle Input
  244. /// <summary>
  245. /// Handles input for quitting the game and cycling
  246. /// through the different particle effects.
  247. /// </summary>
  248. void HandleInput ()
  249. {
  250. lastKeyboardState = currentKeyboardState;
  251. lastGamePadState = currentGamePadState;
  252. currentKeyboardState = Keyboard.GetState ();
  253. currentGamePadState = GamePad.GetState (PlayerIndex.One);
  254. // Check for exit.
  255. if (currentKeyboardState.IsKeyDown (Keys.Escape) ||
  256. currentGamePadState.Buttons.Back == ButtonState.Pressed) {
  257. Exit ();
  258. }
  259. // Check for changing the active particle effect.
  260. if (((currentKeyboardState.IsKeyDown (Keys.Space) &&
  261. (lastKeyboardState.IsKeyUp (Keys.Space))) ||
  262. ((currentGamePadState.Buttons.A == ButtonState.Pressed)) &&
  263. (lastGamePadState.Buttons.A == ButtonState.Released))) {
  264. currentState++;
  265. if (currentState > ParticleState.RingOfFire)
  266. currentState = 0;
  267. }
  268. }
  269. /// <summary>
  270. /// Handles input for moving the camera.
  271. /// </summary>
  272. void UpdateCamera (GameTime gameTime)
  273. {
  274. float time = (float)gameTime.ElapsedGameTime.TotalMilliseconds;
  275. // Check for input to rotate the camera up and down around the model.
  276. if (currentKeyboardState.IsKeyDown (Keys.Up) ||
  277. currentKeyboardState.IsKeyDown (Keys.W)) {
  278. cameraArc += time * 0.025f;
  279. }
  280. if (currentKeyboardState.IsKeyDown (Keys.Down) ||
  281. currentKeyboardState.IsKeyDown (Keys.S)) {
  282. cameraArc -= time * 0.025f;
  283. }
  284. cameraArc += currentGamePadState.ThumbSticks.Right.Y * time * 0.05f;
  285. // Limit the arc movement.
  286. if (cameraArc > 90.0f)
  287. cameraArc = 90.0f;
  288. else if (cameraArc < -90.0f)
  289. cameraArc = -90.0f;
  290. // Check for input to rotate the camera around the model.
  291. if (currentKeyboardState.IsKeyDown (Keys.Right) ||
  292. currentKeyboardState.IsKeyDown (Keys.D)) {
  293. cameraRotation += time * 0.05f;
  294. }
  295. if (currentKeyboardState.IsKeyDown (Keys.Left) ||
  296. currentKeyboardState.IsKeyDown (Keys.A)) {
  297. cameraRotation -= time * 0.05f;
  298. }
  299. cameraRotation += currentGamePadState.ThumbSticks.Right.X * time * 0.1f;
  300. // Check for input to zoom camera in and out.
  301. if (currentKeyboardState.IsKeyDown (Keys.Z))
  302. cameraDistance += time * 0.25f;
  303. if (currentKeyboardState.IsKeyDown (Keys.X))
  304. cameraDistance -= time * 0.25f;
  305. cameraDistance += currentGamePadState.Triggers.Left * time * 0.5f;
  306. cameraDistance -= currentGamePadState.Triggers.Right * time * 0.5f;
  307. // Limit the camera distance.
  308. if (cameraDistance > 500)
  309. cameraDistance = 500;
  310. else if (cameraDistance < 10)
  311. cameraDistance = 10;
  312. if (currentGamePadState.Buttons.RightStick == ButtonState.Pressed ||
  313. currentKeyboardState.IsKeyDown (Keys.R)) {
  314. cameraArc = -5;
  315. cameraRotation = 0;
  316. cameraDistance = 200;
  317. }
  318. }
  319. #endregion
  320. }
  321. #region Entry Point
  322. // /// <summary>
  323. // /// The main entry point for the application.
  324. // /// </summary>
  325. // static class Program
  326. // {
  327. // static void Main()
  328. // {
  329. // using (Particle3DSampleGame game = new Particle3DSampleGame())
  330. // {
  331. // game.Run();
  332. // }
  333. // }
  334. // }
  335. #endregion
  336. }