ShadowMapping.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. #region File Description
  2. //-----------------------------------------------------------------------------
  3. // ShadowMapping.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.Audio;
  14. using Microsoft.Xna.Framework.Content;
  15. using Microsoft.Xna.Framework.GamerServices;
  16. using Microsoft.Xna.Framework.Graphics;
  17. using Microsoft.Xna.Framework.Input;
  18. using Microsoft.Xna.Framework.Net;
  19. using Microsoft.Xna.Framework.Storage;
  20. #endregion
  21. namespace ShadowMapping
  22. {
  23. /// <summary>
  24. /// Sample showing how to implement a simple shadow mapping technique where
  25. /// the shadow map always contains the contents of the viewing frustum
  26. /// </summary>
  27. public class ShadowMappingGame : Microsoft.Xna.Framework.Game
  28. {
  29. #region Constants
  30. // The size of the shadow map
  31. // The larger the size the more detail we will have for our entire scene
  32. const int shadowMapWidthHeight = 2048;
  33. const int windowWidth = 800;
  34. const int windowHeight = 480;
  35. #endregion
  36. #region Fields
  37. GraphicsDeviceManager graphics;
  38. SpriteBatch spriteBatch;
  39. // Starting position and direction of our camera
  40. Vector3 cameraPosition = new Vector3(0, 70, 100);
  41. Vector3 cameraForward = new Vector3(0, -0.4472136f, -0.8944272f);
  42. BoundingFrustum cameraFrustum = new BoundingFrustum(Matrix.Identity);
  43. // Light direction
  44. Vector3 lightDir = new Vector3(-0.3333333f, 0.6666667f, 0.6666667f);
  45. KeyboardState currentKeyboardState;
  46. GamePadState currentGamePadState;
  47. // Our two models in the scene
  48. Model gridModel;
  49. Model dudeModel;
  50. float rotateDude = 0.0f;
  51. // The shadow map render target
  52. RenderTarget2D shadowRenderTarget;
  53. // Transform matrices
  54. Matrix world;
  55. Matrix view;
  56. Matrix projection;
  57. // ViewProjection matrix from the lights perspective
  58. Matrix lightViewProjection;
  59. #endregion
  60. #region Initialization
  61. public ShadowMappingGame()
  62. {
  63. graphics = new GraphicsDeviceManager(this);
  64. Content.RootDirectory = "Content";
  65. graphics.PreferredBackBufferWidth = windowWidth;
  66. graphics.PreferredBackBufferHeight = windowHeight;
  67. float aspectRatio = (float)windowWidth / (float)windowHeight;
  68. projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
  69. aspectRatio,
  70. 1.0f, 1000.0f);
  71. }
  72. /// <summary>
  73. /// LoadContent will be called once per game and is the place to load
  74. /// all of your content.
  75. /// </summary>
  76. protected override void LoadContent()
  77. {
  78. spriteBatch = new SpriteBatch(GraphicsDevice);
  79. // Load the two models we will be using in the sample
  80. gridModel = Content.Load<Model>("grid");
  81. dudeModel = Content.Load<Model>("dude");
  82. // Create floating point render target
  83. shadowRenderTarget = new RenderTarget2D(graphics.GraphicsDevice,
  84. shadowMapWidthHeight,
  85. shadowMapWidthHeight,
  86. false,
  87. SurfaceFormat.Single,
  88. DepthFormat.Depth24);
  89. }
  90. #endregion
  91. #region Update and Draw
  92. /// <summary>
  93. /// Allows the game to run logic such as updating the world,
  94. /// checking for collisions, gathering input, and playing audio.
  95. /// </summary>
  96. /// <param name="gameTime">Provides a snapshot of timing values.</param>
  97. protected override void Update(GameTime gameTime)
  98. {
  99. HandleInput(gameTime);
  100. UpdateCamera(gameTime);
  101. base.Update(gameTime);
  102. }
  103. /// <summary>
  104. /// This is called when the game should draw itself.
  105. /// </summary>
  106. /// <param name="gameTime">Provides a snapshot of timing values.</param>
  107. protected override void Draw(GameTime gameTime)
  108. {
  109. // Update the lights ViewProjection matrix based on the
  110. // current camera frustum
  111. lightViewProjection = CreateLightViewProjectionMatrix();
  112. GraphicsDevice.BlendState = BlendState.Opaque;
  113. GraphicsDevice.DepthStencilState = DepthStencilState.Default;
  114. // Render the scene to the shadow map
  115. CreateShadowMap();
  116. // Draw the scene using the shadow map
  117. DrawWithShadowMap();
  118. // Display the shadow map to the screen
  119. DrawShadowMapToScreen();
  120. base.Draw(gameTime);
  121. }
  122. #endregion
  123. #region Methods
  124. /// <summary>
  125. /// Creates the WorldViewProjection matrix from the perspective of the
  126. /// light using the cameras bounding frustum to determine what is visible
  127. /// in the scene.
  128. /// </summary>
  129. /// <returns>The WorldViewProjection for the light</returns>
  130. Matrix CreateLightViewProjectionMatrix()
  131. {
  132. // Matrix with that will rotate in points the direction of the light
  133. Matrix lightRotation = Matrix.CreateLookAt(Vector3.Zero,
  134. -lightDir,
  135. Vector3.Up);
  136. // Get the corners of the frustum
  137. Vector3[] frustumCorners = cameraFrustum.GetCorners();
  138. // Transform the positions of the corners into the direction of the light
  139. for (int i = 0; i < frustumCorners.Length; i++)
  140. {
  141. frustumCorners[i] = Vector3.Transform(frustumCorners[i], lightRotation);
  142. }
  143. // Find the smallest box around the points
  144. BoundingBox lightBox = BoundingBox.CreateFromPoints(frustumCorners);
  145. Vector3 boxSize = lightBox.Max - lightBox.Min;
  146. Vector3 halfBoxSize = boxSize * 0.5f;
  147. // The position of the light should be in the center of the back
  148. // pannel of the box.
  149. Vector3 lightPosition = lightBox.Min + halfBoxSize;
  150. lightPosition.Z = lightBox.Min.Z;
  151. // We need the position back in world coordinates so we transform
  152. // the light position by the inverse of the lights rotation
  153. lightPosition = Vector3.Transform(lightPosition,
  154. Matrix.Invert(lightRotation));
  155. // Create the view matrix for the light
  156. Matrix lightView = Matrix.CreateLookAt(lightPosition,
  157. lightPosition - lightDir,
  158. Vector3.Up);
  159. // Create the projection matrix for the light
  160. // The projection is orthographic since we are using a directional light
  161. Matrix lightProjection = Matrix.CreateOrthographic(boxSize.X, boxSize.Y,
  162. -boxSize.Z, boxSize.Z);
  163. return lightView * lightProjection;
  164. }
  165. /// <summary>
  166. /// Renders the scene to the floating point render target then
  167. /// sets the texture for use when drawing the scene.
  168. /// </summary>
  169. void CreateShadowMap()
  170. {
  171. // Set our render target to our floating point render target
  172. GraphicsDevice.SetRenderTarget(shadowRenderTarget);
  173. // Clear the render target to white or all 1's
  174. // We set the clear to white since that represents the
  175. // furthest the object could be away
  176. GraphicsDevice.Clear(Color.White);
  177. // Draw any occluders in our case that is just the dude model
  178. // Set the models world matrix so it will rotate
  179. world = Matrix.CreateRotationY(MathHelper.ToRadians(rotateDude));
  180. // Draw the dude model
  181. DrawModel(dudeModel, true);
  182. // Set render target back to the back buffer
  183. GraphicsDevice.SetRenderTarget(null);
  184. }
  185. /// <summary>
  186. /// Renders the scene using the shadow map to darken the shadow areas
  187. /// </summary>
  188. void DrawWithShadowMap()
  189. {
  190. graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
  191. GraphicsDevice.SamplerStates[1] = SamplerState.PointClamp;
  192. // Draw the grid
  193. world = Matrix.Identity;
  194. DrawModel(gridModel, false);
  195. // Draw the dude model
  196. world = Matrix.CreateRotationY(MathHelper.ToRadians(rotateDude));
  197. DrawModel(dudeModel, false);
  198. }
  199. /// <summary>
  200. /// Helper function to draw a model
  201. /// </summary>
  202. /// <param name="model">The model to draw</param>
  203. /// <param name="technique">The technique to use</param>
  204. void DrawModel(Model model, bool createShadowMap)
  205. {
  206. string techniqueName = createShadowMap ? "CreateShadowMap" : "DrawWithShadowMap";
  207. Matrix[] transforms = new Matrix[model.Bones.Count];
  208. model.CopyAbsoluteBoneTransformsTo(transforms);
  209. // Loop over meshs in the model
  210. foreach (ModelMesh mesh in model.Meshes)
  211. {
  212. // Loop over effects in the mesh
  213. foreach (Effect effect in mesh.Effects)
  214. {
  215. // Set the currest values for the effect
  216. effect.CurrentTechnique = effect.Techniques[techniqueName];
  217. effect.Parameters["World"].SetValue(world);
  218. effect.Parameters["View"].SetValue(view);
  219. effect.Parameters["Projection"].SetValue(projection);
  220. effect.Parameters["LightDirection"].SetValue(lightDir);
  221. effect.Parameters["LightViewProj"].SetValue(lightViewProjection);
  222. if (!createShadowMap)
  223. effect.Parameters["ShadowMap"].SetValue(shadowRenderTarget);
  224. }
  225. // Draw the mesh
  226. mesh.Draw();
  227. }
  228. }
  229. /// <summary>
  230. /// Render the shadow map texture to the screen
  231. /// </summary>
  232. void DrawShadowMapToScreen()
  233. {
  234. spriteBatch.Begin(0, BlendState.Opaque, SamplerState.PointClamp, null, null);
  235. spriteBatch.Draw(shadowRenderTarget, new Rectangle(0, 0, 128, 128), Color.White);
  236. spriteBatch.End();
  237. GraphicsDevice.Textures[0] = null;
  238. GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;
  239. }
  240. #endregion
  241. #region Handle Input
  242. /// <summary>
  243. /// Handles input for quitting the game.
  244. /// </summary>
  245. void HandleInput(GameTime gameTime)
  246. {
  247. float time = (float)gameTime.ElapsedGameTime.TotalMilliseconds;
  248. currentKeyboardState = Keyboard.GetState();
  249. currentGamePadState = GamePad.GetState(PlayerIndex.One);
  250. // Rotate the dude model
  251. rotateDude += currentGamePadState.Triggers.Right * time * 0.2f;
  252. rotateDude -= currentGamePadState.Triggers.Left * time * 0.2f;
  253. if (currentKeyboardState.IsKeyDown(Keys.Q))
  254. rotateDude -= time * 0.2f;
  255. if (currentKeyboardState.IsKeyDown(Keys.E))
  256. rotateDude += time * 0.2f;
  257. // Check for exit.
  258. if (currentKeyboardState.IsKeyDown(Keys.Escape) ||
  259. currentGamePadState.Buttons.Back == ButtonState.Pressed)
  260. {
  261. Exit();
  262. }
  263. }
  264. /// <summary>
  265. /// Handles input for moving the camera.
  266. /// </summary>
  267. void UpdateCamera(GameTime gameTime)
  268. {
  269. float time = (float)gameTime.ElapsedGameTime.TotalMilliseconds;
  270. // Check for input to rotate the camera.
  271. float pitch = -currentGamePadState.ThumbSticks.Right.Y * time * 0.001f;
  272. float turn = -currentGamePadState.ThumbSticks.Right.X * time * 0.001f;
  273. if (currentKeyboardState.IsKeyDown(Keys.Up))
  274. pitch += time * 0.001f;
  275. if (currentKeyboardState.IsKeyDown(Keys.Down))
  276. pitch -= time * 0.001f;
  277. if (currentKeyboardState.IsKeyDown(Keys.Left))
  278. turn += time * 0.001f;
  279. if (currentKeyboardState.IsKeyDown(Keys.Right))
  280. turn -= time * 0.001f;
  281. Vector3 cameraRight = Vector3.Cross(Vector3.Up, cameraForward);
  282. Vector3 flatFront = Vector3.Cross(cameraRight, Vector3.Up);
  283. Matrix pitchMatrix = Matrix.CreateFromAxisAngle(cameraRight, pitch);
  284. Matrix turnMatrix = Matrix.CreateFromAxisAngle(Vector3.Up, turn);
  285. Vector3 tiltedFront = Vector3.TransformNormal(cameraForward, pitchMatrix *
  286. turnMatrix);
  287. // Check angle so we cant flip over
  288. if (Vector3.Dot(tiltedFront, flatFront) > 0.001f)
  289. {
  290. cameraForward = Vector3.Normalize(tiltedFront);
  291. }
  292. // Check for input to move the camera around.
  293. if (currentKeyboardState.IsKeyDown(Keys.W))
  294. cameraPosition += cameraForward * time * 0.1f;
  295. if (currentKeyboardState.IsKeyDown(Keys.S))
  296. cameraPosition -= cameraForward * time * 0.1f;
  297. if (currentKeyboardState.IsKeyDown(Keys.A))
  298. cameraPosition += cameraRight * time * 0.1f;
  299. if (currentKeyboardState.IsKeyDown(Keys.D))
  300. cameraPosition -= cameraRight * time * 0.1f;
  301. cameraPosition += cameraForward *
  302. currentGamePadState.ThumbSticks.Left.Y * time * 0.1f;
  303. cameraPosition -= cameraRight *
  304. currentGamePadState.ThumbSticks.Left.X * time * 0.1f;
  305. if (currentGamePadState.Buttons.RightStick == ButtonState.Pressed ||
  306. currentKeyboardState.IsKeyDown(Keys.R))
  307. {
  308. cameraPosition = new Vector3(0, 50, 50);
  309. cameraForward = new Vector3(0, 0, -1);
  310. }
  311. cameraForward.Normalize();
  312. // Create the new view matrix
  313. view = Matrix.CreateLookAt(cameraPosition,
  314. cameraPosition + cameraForward,
  315. Vector3.Up);
  316. // Set the new frustum value
  317. cameraFrustum.Matrix = view * projection;
  318. }
  319. #endregion
  320. }
  321. }