} // RocketCommanderXnaGame() /// <summary> /// Initialize textures and models for the game. /// </summary> protected override void Initialize() { base.Initialize(); // Load all available levels levels = Level.LoadAllLevels(); // Initialize asteroidManager and use last avialable level. asteroidManager = new GameAsteroidManager(levels[levels.Length - 1]); rocketModel = new Model("Rocket"); // Load menu textures mainMenuTexture = new Texture("MainMenu.png"); helperTexture = new Texture("ExtraButtons.png"); helpScreenTexture = new Texture("HelpScreen.png"); mouseCursorTexture = new Texture("MouseCursor.dds"); hudTexture = new Texture("Hud.png"); inGameTexture = new Texture("InGame.png"); lightEffectTexture = new Texture("LightEffect.dds"); explosionTexture = new AnimatedTexture("Explosion"); // Create main menu screen gameScreens.Push(new MainMenu()); //tst: //gameScreens.Push(new Mission(levels[0], asteroidManager)); //inGame = gameScreens.Peek().GetType() == typeof(Mission); //camera.InGame = inGame; } // Initialize()
} // Show() #endregion #region Unit Testing #if DEBUG /// <summary> /// Test post screen glow /// </summary> public static void TestPostScreenGlow() { Model testModel = null; PostScreenGlow glowShader = null; TestGame.Start("TestPostScreenGlow", delegate { testModel = new Model("Asteroid2"); glowShader = new PostScreenGlow(); }, delegate { //Thread.Sleep(10); glowShader.Start(); BaseGame.skyCube.RenderSky(); testModel.Render(Vector3.Zero); BaseGame.MeshRenderManager.Render(); if (Input.Keyboard.IsKeyDown(Keys.LeftAlt) == false && Input.GamePadAPressed == false) { glowShader.Show(); } else { // Resolve first glowShader.sceneMapTexture.Resolve(false); started = false; // Reset background buffer RenderToTexture.ResetRenderTarget(true); // Just show scene map glowShader.sceneMapTexture.RenderOnScreen(BaseGame.ResolutionRect); } // else TextureFont.WriteText(2, 30, "Press left alt or A to just show the unchanged screen."); TextureFont.WriteText(2, 60, "Press space or B to see all menu post screen render passes."); //*TODO if (Input.Keyboard.IsKeyDown(Keys.Space) || // == false) Input.GamePadBPressed) { glowShader.sceneMapTexture.RenderOnScreen( new Rectangle(10, 10, 256, 256)); glowShader.downsampleMapTexture.RenderOnScreen( new Rectangle(10 + 256 + 10, 10, 256, 256)); glowShader.blurMap1Texture.RenderOnScreen( new Rectangle(10 + 256 + 10 + 256 + 10, 10, 256, 256)); glowShader.blurMap2Texture.RenderOnScreen( new Rectangle(10, 10 + 256 + 10, 256, 256)); } // if (Input.Keyboard.IsKeyDown) }); } // TestPostScreenGlow()
} // Dispose(someObject) /// <summary> /// Dispose /// </summary> /// <param name="someObject">Some object</param> public static void Dispose(ref Model someObject) { if (someObject != null) { someObject.Dispose(); } someObject = null; } // Dispose(someObject)
/// <summary> /// Create asteroid manager /// </summary> public GameAsteroidManager(Level setLevel) : base(setLevel) { // Load all items for (int num = 0; num < Level.NumOfItemTypes; num++) { // All items are animated, load with help of AnimatedModel. itemModels[num] = new AnimatedModel(ItemModelFilenames[num]); } // for (num) // Load hit direction texture hitDirectionTexture = new Texture("HitDirection.dds"); // Load goal model goalModel = new Model("Goal"); } // AsteroidManager()
/// <summary> /// Zoom into rocket /// </summary> /// <param name="camera">Camera</param> private void ZoomIntoRocket(SpaceCamera camera, Model rocketModel) { if (Player.GameOver) { // Only start showing rocket after all explosions are nearly over! // Only 400ms left. if (Player.explosionTimeoutMs < 400 && Player.explosionTimeoutMs2 < 400 && Player.explosionTimeoutMs3 < 400) { // Make sure z buffer is on BaseGame.Device.RenderState.DepthBufferEnable = true; // Scale in rocket (cool zoom effect) rocketEndGameScale += BaseGame.MoveFactorPerSecond * 5.0f; if (rocketEndGameScale > 10.0f) rocketEndGameScale = 10.0f; float scale = rocketEndGameScale; // Show rocket in middle of screen. Vector3 inFrontOfCameraPos = new Vector3(0, -0.3f, -1.75f) * 10.0f; inFrontOfCameraPos = Vector3.TransformNormal( inFrontOfCameraPos, BaseGame.InverseViewMatrix); Matrix startMatrix = Matrix.CreateScale(scale, scale, scale) * Matrix.CreateRotationX((float)Math.PI / 2.0f) * Matrix.CreateRotationY(BaseGame.TotalTimeMs / 2293.0f) * Matrix.CreateRotationX(-(float)Math.PI) * Matrix.CreateRotationZ((float)Math.PI / 4.0f) * Matrix.CreateTranslation(inFrontOfCameraPos + BaseGame.CameraPos); rocketModel.Render(startMatrix); // Disable z buffer, now only 2d content is rendered. BaseGame.Device.RenderState.DepthBufferEnable = false; } // if else rocketEndGameScale = 0.0f; } // if }
/// <summary> /// Create asteroid manager /// </summary> public BaseAsteroidManager(Level setLevel) { // Set level CurrentLevel = setLevel; // Load all available asteroids int asteroidNum = 1; while (File.Exists(Directories.ContentDirectory + "\\" + "Asteroid" + asteroidNum + "." + Directories.ContentExtension)) { Model asteroidModel = new Model("Asteroid" + asteroidNum); asteroidModels.Add(asteroidModel); // Try to use low version of asteroid if (File.Exists(Directories.ContentDirectory + "\\" + "Asteroid" + asteroidNum + "Low." + Model.Extension)) asteroidModelsLow.Add(new Model("Asteroid" + asteroidNum + "Low")); else // If none is found, use normal one. asteroidModelsLow.Add(asteroidModel); asteroidNum++; } // while (File.Exists) if (asteroidModels.Count == 0) throw new Exception("Unable to start game, no asteroid models were " + "found, please check the Models directory!"); // Load all small asteroids int smallAsteroidNum = 1; while (File.Exists(Directories.ContentDirectory + "\\" + "SmallAsteroid" + smallAsteroidNum + "." + Directories.ContentExtension)) { smallAsteroidModels.Add(new Model("SmallAsteroid" + smallAsteroidNum)); smallAsteroidNum++; } // while (File.Exists) // Create all asteroids for (int z = MinSector; z <= MaxSector; z++) for (int x = MinSector; x <= MaxSector; x++) { int iz = z + MiddleSector, ix = x + MiddleSector; sectorAsteroids[iz, ix] = new List<Asteroid>(); GenerateSector(sectorAsteroids[iz, ix], x, z); } // for for for (int) // Create smaller asteroids for (int z = MinSmallSector; z <= MaxSmallSector; z++) //for (int y = MinSmallSector; y <= MaxSmallSector; y++) for (int x = MinSmallSector; x <= MaxSmallSector; x++) { int iz = z + SmallMiddleSector, //iy = y + SmallMiddleSector, ix = x + SmallMiddleSector; sectorSmallerAsteroids[iz, ix] = new List<SmallAsteroids>(); GenerateSmallerAsteroidsSector( sectorSmallerAsteroids[iz, ix], sectorAsteroids[iz + SmallSectorAdd,// iy + SmallSectorAdd, ix + SmallSectorAdd].Count, x, z); } // for for for (int) // Precalculate visible sector stuff for (int z = MinSector; z <= MaxSector; z++) for (int x = MinSector; x <= MaxSector; x++) { int iz = z + MiddleSector, ix = x + MiddleSector; // Check if distance (that sqrt thingy) is smaller than // the max view depth (in int this is MiddleSector) and add // a small offset (0.25) to include nearly visible sectors. sectorVisibleInRange[iz, ix] = (float)Math.Sqrt(x * x + z * z) < MiddleSector + 0.25f; // Calculate direction (just normalize relative position) sectorDirection[iz, ix] = -new Vector3(x, 0, z); sectorDirection[iz, ix].Normalize(); } // for for for (int) // Calculate sectors and visibility CalculateSectors(); physicsThread = new Thread(new ThreadStart(PhysicsUpdate)); physicsThread.Start(); }
/// <summary> /// Test rendering asteroids for Tutorial 2. /// We want just to display a bunch of asteroids in 3d space. /// </summary> public static void TestRenderingAsteroids() { List<Asteroid> heinoAsteroids = new List<Asteroid>(); heinoAsteroids.Add(new Asteroid( 4, Vector3.Zero));//, 1.0f)); heinoAsteroids.Add(new Asteroid( 4, new Vector3(100, 0, 0)));//, 3.0f)); heinoAsteroids.Add(new Asteroid( 4, new Vector3(0, 100, 0)));//, 0.5f)); Model asteroidModel = null; TestGame.Start("Test rendering asteroids", delegate { asteroidModel = new Model("Asteroid5.x"); }, delegate { foreach (Asteroid asteroid in heinoAsteroids) asteroidModel.Render(asteroid.RenderMatrix); }); }
/*perf test code public static long updateThreadMs = 0; public static long updateThreadTicks = 0; */ /*tst public static long physicsThreadMs = 0; public static long physicsThreadTicks = 0; */ #endregion Other #if DEBUG /// <summary> /// Basically test the BaseAsteroidManager class. /// </summary> public static void TestAsteroidManager() { //already done in TestGame: BaseAsteroidManager asteroidManager = null; Model testModel = null; TestGame.Start("Test asteroid manager", delegate { asteroidManager = new BaseAsteroidManager( Level.LoadAllLevels()[0]); testModel = new Model("asteroid5"); }, delegate { BaseGame.GlowShader.Start(); // Render sky cube map as our background. BaseGame.skyCube.RenderSky(1.0f, BaseGame.SkyBackgroundColor); //testModel.Render(Matrix.CreateScale(50), // 1.0f - BaseGame.CameraPos.Length() / 500); asteroidManager.RenderAsteroids(); /*tst BaseGame.DrawLine(Vector3.Zero, new Vector3(1000, 0, 0), Color.Red); BaseGame.DrawLine(Vector3.Zero, new Vector3(0, 0, 1000), Color.Green); TextureFont.WriteText(2, 30, "Camera pos=" + BaseGame.CameraPos); TextureFont.WriteText(2, 60, "FarPlane=" + BaseGame.FarPlane); TextureFont.WriteText(2, 90, "Distance=" + BaseGame.CameraPos.Length()); TextureFont.WriteText(2, 120, "HalfViewDepth=" + HalfViewDepth); TextureFont.WriteText(2, 150, "NumberOfSectors=" + BaseAsteroidManager.NumberOfSectors); for (int x=0; x<19; x++) for (int z=0; z<19; z++) TextureFont.WriteText(300+x*15, 100+z*20, asteroidManager.sectorIsVisible[x, z] ? "*":"."); //*/ }); }
//*/ /// <summary> /// Test create render to texture /// </summary> public static void TestCreateRenderToTexture() { Model testModel = null; RenderToTexture renderToTexture = null; TestGame.Start( "TestCreateRenderToTexture", delegate { testModel = new Model("asteroid1"); renderToTexture = new RenderToTexture( //SizeType.QuarterScreen); SizeType.HalfScreen); //SizeType.HalfScreenWithZBuffer); //SizeType.FullScreen); //SizeType.ShadowMap); }, delegate { bool renderToTextureWay = Input.Keyboard.IsKeyUp(Keys.Space) && Input.GamePadAPressed == false; BaseGame.Device.RenderState.DepthBufferEnable = true; if (renderToTextureWay) { // Set render target to our texture renderToTexture.SetRenderTarget(); // Clear background renderToTexture.Clear(Color.Blue); // Draw background lines //Line.DrawGrid(); //Ui.LineManager.RenderAll3DLines(); // And draw object testModel.Render(Matrix.CreateScale(7.5f)); //BaseGame.RenderManager.RenderAllMeshes(); // Do we need to resolve? renderToTexture.Resolve(true); //BaseGame.Device.ResolveRenderTarget(0); // Reset background buffer //not longer required, done in Resolve now: //RenderToTexture.ResetRenderTarget(true); } // if (renderToTextureWay) else { // Copy backbuffer way, render stuff normally first // Clear background BaseGame.Device.Clear(Color.Blue); // Draw background lines //Line.DrawGrid(); //Ui.LineManager.RenderAll3DLines(); // And draw object testModel.Render(Matrix.CreateScale(7.5f)); //BaseGame.RenderManager.RenderAllMeshes(); } // else // Show render target in a rectangle on our screen renderToTexture.RenderOnScreen( //tst: new Rectangle(100, 100, 256, 256)); //BaseGame.ScreenRectangle); //no need: BaseGame.UI.FlushUI(); TextureFont.WriteText(2, 0, " Press Space to toogle full screen rendering"); TextureFont.WriteText(2, 30, "renderToTexture.Width=" + renderToTexture.Width); TextureFont.WriteText(2, 60, "renderToTexture.Height=" + renderToTexture.Height); TextureFont.WriteText(2, 90, "renderToTexture.Valid=" + renderToTexture.IsValid); TextureFont.WriteText(2, 120, "renderToTexture.XnaTexture=" + renderToTexture.XnaTexture); TextureFont.WriteText(2, 150, "renderToTexture.ZBufferSurface=" + renderToTexture.ZBufferSurface); TextureFont.WriteText(2, 180, "renderToTexture.Filename=" + renderToTexture.Filename); }); }
/// <summary> /// Dispose /// </summary> /// <param name="someObject">Some object</param> public static void Dispose(ref Model someObject) { if (someObject != null) someObject.Dispose(); someObject = null; }
/*obs /// <summary> /// Create space camera /// </summary> /// <param name="setCameraPos">Set camera pos</param> /// <param name="setRotationQuaternion">Set rotation quaternion</param> public SpaceCamera(BaseGame game, Vector3 setCameraPos, Quaternion setRotationQuaternion) : this(game, setCameraPos) { quaternion = setRotationQuaternion; } // SpaceCamera(game, setCameraPos, setRotationQuaternion) */ /*obs /// <summary> /// Rotate /// </summary> /// <param name="axis">Axis</param> /// <param name="angle">Angle</param> private void Rotate(Vector3 axis, float angle) { quaternion *= Quaternion.CreateFromAxisAngle(axis, angle); } // Rotate(axis, angle) */ #endregion Other #if DEBUG /// <summary> /// Test space camera /// </summary> public static void TestSpaceCamera() { Model testModel = null; TestGame.Start("TestSpaceCamera", delegate // Init { testModel = new Model("asteroid4"); }, delegate // Render loop { // Just render testModel in the middle of the scene. testModel.Render(Vector3.Zero); TextureFont.WriteText(1, 20, "MoveFactorPerSecond=" + BaseGame.MoveFactorPerSecond); }); }
/// <summary> /// Create asteroid manager /// </summary> public GameAsteroidManager(Level setLevel) : base(setLevel) { // Load all items for (int num = 0; num < Level.NumOfItemTypes; num++) { // All items are animated, load with help of AnimatedModel. itemModels[num] = new AnimatedModel(ItemModelFilenames[num]); } // for (num) // Load hit direction texture hitDirectionTexture = new Texture("HitDirection.dds"); // Load goal model goalModel = new Model("Goal"); }
/// <summary> /// Initialize textures and models for the game. /// </summary> protected override void Initialize() { base.Initialize(); // Load all available levels levels = Level.LoadAllLevels(); // Initialize asteroidManager and use last avialable level. asteroidManager = new GameAsteroidManager(levels[levels.Length - 1]); rocketModel = new Model("Rocket"); // Load menu textures mainMenuTexture = new Texture("MainMenu.png"); helperTexture = new Texture("ExtraButtons.png"); helpScreenTexture = new Texture("HelpScreen.png"); mouseCursorTexture = new Texture("MouseCursor.dds"); hudTexture = new Texture("Hud.png"); inGameTexture = new Texture("InGame.png"); lightEffectTexture = new Texture("LightEffect.dds"); explosionTexture = new AnimatedTexture("Explosion"); // Create main menu screen gameScreens.Push(new MainMenu()); //tst: //gameScreens.Push(new Mission(levels[0], asteroidManager)); //inGame = gameScreens.Peek().GetType() == typeof(Mission); //camera.InGame = inGame; }
} // ResetRenderTarget(fullResetToBackBuffer) #endregion #region Unit Testing #if DEBUG /// <summary> /// Test create render to texture /// </summary> static public void TestCreateRenderToTexture() { Model testModel = null; RenderToTexture renderToTexture = null; TestGame.Start( "TestCreateRenderToTexture", delegate { testModel = new Model("asteroid1"); renderToTexture = new RenderToTexture( //SizeType.QuarterScreen); SizeType.HalfScreen); //SizeType.HalfScreenWithZBuffer); //SizeType.FullScreen); //SizeType.ShadowMap); }, delegate { bool renderToTextureWay = Input.Keyboard.IsKeyUp(Keys.Space) && Input.GamePadAPressed == false; BaseGame.Device.RenderState.DepthBufferEnable = true; if (renderToTextureWay) { // Set render target to our texture renderToTexture.SetRenderTarget(); // Clear background renderToTexture.Clear(Color.Blue); // Draw background lines //Line.DrawGrid(); //Ui.LineManager.RenderAll3DLines(); // And draw object testModel.Render(Matrix.CreateScale(7.5f)); //BaseGame.RenderManager.RenderAllMeshes(); // Do we need to resolve? renderToTexture.Resolve(true); //BaseGame.Device.ResolveRenderTarget(0); // Reset background buffer //not longer required, done in Resolve now: //RenderToTexture.ResetRenderTarget(true); } // if (renderToTextureWay) else { // Copy backbuffer way, render stuff normally first // Clear background BaseGame.Device.Clear(Color.Blue); // Draw background lines //Line.DrawGrid(); //Ui.LineManager.RenderAll3DLines(); // And draw object testModel.Render(Matrix.CreateScale(7.5f)); //BaseGame.RenderManager.RenderAllMeshes(); } // else // Show render target in a rectangle on our screen renderToTexture.RenderOnScreen( //tst: new Rectangle(100, 100, 256, 256)); //BaseGame.ScreenRectangle); //no need: BaseGame.UI.FlushUI(); TextureFont.WriteText(2, 0, " Press Space to toogle full screen rendering"); TextureFont.WriteText(2, 30, "renderToTexture.Width=" + renderToTexture.Width); TextureFont.WriteText(2, 60, "renderToTexture.Height=" + renderToTexture.Height); TextureFont.WriteText(2, 90, "renderToTexture.Valid=" + renderToTexture.IsValid); TextureFont.WriteText(2, 120, "renderToTexture.XnaTexture=" + renderToTexture.XnaTexture); TextureFont.WriteText(2, 150, "renderToTexture.ZBufferSurface=" + renderToTexture.ZBufferSurface); TextureFont.WriteText(2, 180, "renderToTexture.Filename=" + renderToTexture.Filename); }); } // TestCreateRenderToTexture()
/// <summary> /// Test asteroid manager physics. Press 1-7 to start physics scenes. /// </summary> public void TestAsteroidPhysicsSmallScene() { TestGame.Start("TestAsteroidPhysicsSmallScene", delegate { asteroidManager = new GameAsteroidManager( Level.LoadAllLevels()[0]); asteroidModel = asteroidManager.asteroidModels[0]; //new Model("Asteroid1.X"); SetupScene(0); }, delegate { BaseGame.GlowShader.Start(); // Render sky cube map as our background. BaseGame.skyCube.RenderSky(1.0f, BaseGame.SkyBackgroundColor); BaseGame.camera.FreeCamera = true; BaseGame.EnableAlphaBlending(); // Press 1-7 to start physics scenes. if (Input.KeyboardKeyJustPressed(Keys.D1)) SetupScene(0); if (Input.KeyboardKeyJustPressed(Keys.D2)) SetupScene(1); if (Input.KeyboardKeyJustPressed(Keys.D3)) SetupScene(2); if (Input.KeyboardKeyJustPressed(Keys.D4)) SetupScene(3); if (Input.KeyboardKeyJustPressed(Keys.D5)) SetupScene(4); if (Input.KeyboardKeyJustPressed(Keys.D6)) SetupScene(5); if (Input.KeyboardKeyJustPressed(Keys.D7)) SetupScene(6); for (int z = 0; z < NumberOfSectors; z++) //for (int y = 0; y < NumberOfSectors; y++) for (int x = 0; x < NumberOfSectors; x++) { // Update all positions for this sector foreach (Asteroid asteroid in asteroidManager.sectorAsteroids[z, x]) asteroid.UpdateMovement(BaseGame.MoveFactorPerSecond); // Handle physics (only calculate 50% per frame) //always: if ((z + x) % 2 == BaseGame.TotalFrames % 2) asteroidManager.HandleSectorPhysics(x, z, 0, 0); } // asteroidModel // Make sure we start the mesh render manager for this frame. // It will copy all models from last frame over to this frame. //obs, handled in render now! BaseGame.MeshRenderManager.Init(); // Render physics asteroids ourselfs for (int z = 0; z < NumberOfSectors; z++) //for (int y = 0; y < NumberOfSectors; y++) for (int x = 0; x < NumberOfSectors; x++) //if (x <= 1 && y <= 1 && z <= 1) if (asteroidManager.sectorIsVisible[z, x]) foreach (Asteroid asteroid in asteroidManager.sectorAsteroids[z, x]) { asteroidModel.Render(asteroid.RenderMatrix); } // asteroidModel }); }
/// <summary> /// Test post screen glow /// </summary> public static void TestPostScreenGlow() { Model testModel = null; PostScreenGlow glowShader = null; TestGame.Start("TestPostScreenGlow", delegate { testModel = new Model("Asteroid2"); glowShader = new PostScreenGlow(); }, delegate { //Thread.Sleep(10); glowShader.Start(); BaseGame.skyCube.RenderSky(); testModel.Render(Vector3.Zero); BaseGame.MeshRenderManager.Render(); if (Input.Keyboard.IsKeyDown(Keys.LeftAlt) == false && Input.GamePadAPressed == false) glowShader.Show(); else { // Resolve first glowShader.sceneMapTexture.Resolve(false); started = false; // Reset background buffer RenderToTexture.ResetRenderTarget(true); // Just show scene map glowShader.sceneMapTexture.RenderOnScreen(BaseGame.ResolutionRect); } // else TextureFont.WriteText(2, 30, "Press left alt or A to just show the unchanged screen."); TextureFont.WriteText(2, 60, "Press space or B to see all menu post screen render passes."); //*TODO if (Input.Keyboard.IsKeyDown(Keys.Space) ||// == false) Input.GamePadBPressed) { glowShader.sceneMapTexture.RenderOnScreen( new Rectangle(10, 10, 256, 256)); glowShader.downsampleMapTexture.RenderOnScreen( new Rectangle(10 + 256 + 10, 10, 256, 256)); glowShader.blurMap1Texture.RenderOnScreen( new Rectangle(10 + 256 + 10 + 256 + 10, 10, 256, 256)); glowShader.blurMap2Texture.RenderOnScreen( new Rectangle(10, 10 + 256 + 10, 256, 256)); } // if (Input.Keyboard.IsKeyDown) }); }