ShadowMapping.cs 15 KB

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