Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Runtime.InteropServices;
- using Microsoft.Xna.Framework;
- using Microsoft.Xna.Framework.Audio;
- using Microsoft.Xna.Framework.Content;
- using Microsoft.Xna.Framework.GamerServices;
- using Microsoft.Xna.Framework.Graphics;
- using Microsoft.Xna.Framework.Input;
- using Microsoft.Xna.Framework.Net;
- using Microsoft.Xna.Framework.Storage;
- namespace MyFirst3D
- {
- /// <summary>
- /// This is the main type for your game
- /// </summary>
- public class Game1 : Microsoft.Xna.Framework.Game
- {
- public struct VertexPositionColorNormal
- {
- public Vector3 Position;
- public Color Color;
- public Vector3 Normal;
- public readonly static VertexDeclaration VertexDeclaration = new VertexDeclaration
- (
- new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0),
- new VertexElement(sizeof(float) * 3, VertexElementFormat.Color, VertexElementUsage.Color, 0),
- new VertexElement(sizeof(float) * 3 + 4, VertexElementFormat.Vector3, VertexElementUsage.Normal, 0)
- );
- }
- [DllImport("user32.dll", CharSet = CharSet.Auto)]
- public static extern uint MessageBox(IntPtr hWnd, String text, String caption, uint type);
- //*** Camera Part***\\
- float leftrightRot = MathHelper.PiOver2;
- float updownRot = -MathHelper.Pi / 10.0f;
- const float rotationSpeed = 0.3f;
- const float moveSpeed = 30.0f;
- //*************************************\\
- VertexBuffer myVertexBuffer;
- IndexBuffer myIndexBuffer;
- GraphicsDeviceManager graphics;
- GraphicsDevice device;
- SpriteBatch spriteBatch;
- Model myModel;
- float aspectRatio;
- FpsMonitor fpsm;
- private SpriteFont Arial10;
- Vector3 cameraPosition;
- MouseState previousState;
- MouseState currentState;
- const float MAXDELAY = 0.5f; // seconds
- DateTime previousClick;
- Effect effect;
- VertexPositionColorNormal[] vertices;
- Matrix viewMatrix;
- Matrix projectionMatrix;
- int[] indices;
- Matrix worldMatrix;
- Matrix rotation;
- MouseState originalMouseState;
- private float angle = 0f;
- private float angleRightLeft = 0f;
- private float angleUpDown = 0f;
- private int terrainWidth = 4;
- private int terrainHeight = 3;
- private float[,] heightData;
- public Game1()
- {
- graphics = new GraphicsDeviceManager(this);
- Content.RootDirectory = "Content";
- }
- /// <summary>
- /// Allows the game to perform any initialization it needs to before starting to run.
- /// This is where it can query for any required services and load any non-graphic
- /// related content. Calling base.Initialize will enumerate through any components
- /// and initialize them as well.
- /// </summary>
- protected override void Initialize()
- {
- // TODO: Add your initialization logic here
- base.Initialize();
- //*** Camera Part***\\
- Matrix cameraRotation = Matrix.CreateRotationX(updownRot) * Matrix.CreateRotationY(leftrightRot);
- Vector3 cameraOriginalTarget = new Vector3(0, 0, -1);
- Vector3 cameraRotatedTarget = Vector3.Transform(cameraOriginalTarget, cameraRotation);
- Vector3 cameraFinalTarget = cameraPosition + cameraRotatedTarget;
- Vector3 cameraOriginalUpVector = new Vector3(0, 1, 0);
- Vector3 cameraRotatedUpVector = Vector3.Transform(cameraOriginalUpVector, cameraRotation);
- viewMatrix = Matrix.CreateLookAt(cameraPosition, cameraFinalTarget, cameraRotatedUpVector);
- //*******************************************************************************************\\
- rotation = Matrix.Identity;
- fpsm = new FpsMonitor(); // in constructor
- this.IsMouseVisible = true;
- cameraPosition = new Vector3(0.0f, 50.0f, 5000.0f);
- //this.graphics.PreferredBackBufferWidth = 1920;
- //this.graphics.PreferredBackBufferHeight = 1080;
- //this.graphics.IsFullScreen = true;
- this.graphics.ApplyChanges();
- }
- /// <summary>
- /// LoadContent will be called once per game and is the place to load
- /// all of your content.
- /// </summary>
- protected override void LoadContent()
- {
- spriteBatch = new SpriteBatch(GraphicsDevice);
- device = graphics.GraphicsDevice;
- Mouse.SetPosition(GraphicsDevice.Viewport.Width / 2, GraphicsDevice.Viewport.Height / 2);//device.Viewport.Width / 2, device.Viewport.Height / 2);
- originalMouseState = Mouse.GetState();
- currentState = Mouse.GetState();
- UpdateViewMatrix(viewMatrix);
- // The aspect ratio determines how to scale 3d to 2d projection.
- // Create a new SpriteBatch, which can be used to draw textures.
- // Create a new SpriteBatch, which can be used to draw textures.
- spriteBatch = new SpriteBatch(GraphicsDevice);
- effect = Content.Load<Effect>("effects"); SetUpCamera();
- Texture2D heightMap = Content.Load<Texture2D>("heightmap"); LoadHeightData(heightMap);
- SetUpVertices();
- SetUpIndices();
- CalculateNormals();
- myModel = Content.Load<Model>("Models\\p1_wedge");
- aspectRatio = graphics.GraphicsDevice.Viewport.AspectRatio;
- Arial10 = Content.Load<SpriteFont>("Consolas");
- // TODO: use this.Content to load your game content here
- worldMatrix = Matrix.CreateTranslation(-terrainWidth / 2.0f, 0, terrainHeight / 2.0f) * Matrix.CreateRotationY(angle);
- CopyToBuffers();
- }
- /// <summary>
- /// UnloadContent will be called once per game and is the place to unload
- /// all content.
- /// </summary>
- protected override void UnloadContent()
- {
- // TODO: Unload any non ContentManager content here
- }
- /// <summary>
- /// Allows the game to run logic such as updating the world,
- /// checking for collisions, gathering input, and playing audio.
- /// </summary>
- /// <param name="gameTime">Provides a snapshot of timing values.</param>
- protected override void Update(GameTime gameTime)
- {
- //angle += 0.005f;
- fpsm.Update();// in update I think first line
- // Allows the game to exit
- if (GamePad.GetState(PlayerIndex.One).Buttons.Back ==
- ButtonState.Pressed)
- this.Exit();
- float timeDifference = (float)gameTime.ElapsedGameTime.TotalMilliseconds / 1000.0f;
- ProcessInput(timeDifference);
- ProcessInputCamera(timeDifference);
- UpdateViewMatrix(viewMatrix);
- modelRotation += (float)gameTime.ElapsedGameTime.TotalMilliseconds *
- MathHelper.ToRadians(0.1f);
- base.Update(gameTime);
- }
- /// <summary>
- /// This is called when the game should draw itself.
- /// </summary>
- /// <param name="gameTime">Provides a snapshot of timing values.</param>
- // Set the position of the model in world space, and set the rotation.
- Vector3 modelPosition = Vector3.Zero;
- float modelRotation = 0.0f;
- // Set the position of the camera in world space, for our view matrix.
- //Vector3 cameraPosition = new Vector3(0.0f, 50.0f, 5000.0f);
- protected override void Draw(GameTime gameTime)
- {
- graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
- //device.Clear(Color.Black);
- device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1.0f, 0);
- RasterizerState rs = new RasterizerState();
- rs.CullMode = CullMode.None;
- // When your run this code, you will indeed see a nicely colored network of lines. When we want to see the whole colored terrain, we just have to remove this line (or set it to FillMode.Solid):
- //rs.FillMode = FillMode.WireFrame;
- device.RasterizerState = rs;
- //Matrix worldMatrix = Matrix.CreateTranslation(-terrainWidth / 2.0f, 0, terrainHeight / 2.0f);
- //worldMatrix = Matrix.CreateTranslation(-terrainWidth / 2.0f, 0, terrainHeight / 2.0f) * Matrix.CreateRotationY(angle);
- /*if (rotationDirection == true)
- {
- worldMatrix = Matrix.CreateFromAxisAngle(this.rotation.Left, angleRightLeft);
- worldMatrix = Matrix.CreateTranslation(-terrainWidth / 2.0f, 0, terrainHeight / 2.0f) * Matrix.CreateRotationY(angleRightLeft);
- }
- else
- {
- worldMatrix = Matrix.CreateTranslation(-terrainWidth / 2.0f, 0, terrainHeight / 2.0f) * Matrix.CreateRotationX(angleUpDown);
- }*/
- worldMatrix = Matrix.CreateTranslation(-terrainWidth / 2.0f, 0, terrainHeight / 2.0f) * Matrix.CreateRotationX(angleUpDown) * Matrix.CreateRotationY(angleRightLeft);
- effect.CurrentTechnique = effect.Techniques["Colored"];
- Vector3 lightDirection = new Vector3(1.0f, -1.0f, -1.0f);
- lightDirection.Normalize();
- effect.Parameters["xLightDirection"].SetValue(lightDirection);
- effect.Parameters["xAmbient"].SetValue(0.6f); effect.Parameters["xEnableLighting"].SetValue(true);
- effect.Parameters["xView"].SetValue(viewMatrix);
- effect.Parameters["xProjection"].SetValue(projectionMatrix);
- effect.Parameters["xWorld"].SetValue(worldMatrix);
- foreach (EffectPass pass in effect.CurrentTechnique.Passes)
- {
- pass.Apply();
- //device.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, vertices, 0, vertices.Length, indices, 0, indices.Length / 3, VertexPositionColorNormal.VertexDeclaration);
- device.Indices = myIndexBuffer;
- device.SetVertexBuffer(myVertexBuffer);
- device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vertices.Length, 0, indices.Length / 3);
- }
- // Copy any parent transforms.
- Matrix[] transforms = new Matrix[myModel.Bones.Count];
- myModel.CopyAbsoluteBoneTransformsTo(transforms);
- // Draw the model. A model can have multiple meshes, so loop.
- foreach (ModelMesh mesh in myModel.Meshes)
- {
- // This is where the mesh orientation is set, as well
- // as our camera and projection.
- foreach (BasicEffect Effect in mesh.Effects)
- {
- Effect.EnableDefaultLighting();
- Effect.World = transforms[mesh.ParentBone.Index] *
- Matrix.CreateRotationY(modelRotation)
- * Matrix.CreateTranslation(modelPosition);
- Effect.View = Matrix.CreateLookAt(cameraPosition,
- Vector3.Zero, Vector3.Up);
- Effect.Projection = Matrix.CreatePerspectiveFieldOfView(
- MathHelper.ToRadians(45.0f), aspectRatio,
- 1.0f, 10000.0f);
- }
- // Draw the mesh, using the effects set above.
- mesh.Draw();
- }
- base.Draw(gameTime);
- spriteBatch.Begin(); // in draw Last lines probably even after base.Draw(gameTime);
- fpsm.Draw(spriteBatch, Arial10, new Vector2(5, 5), Color.White);
- spriteBatch.End();
- }
- /*private void UpdateViewMatrix()
- {
- }*/
- private void ProcessInput(float amount)
- {
- previousState = currentState;
- currentState = Mouse.GetState();
- Vector3 moveVector = new Vector3(0 , 0 , 0);
- KeyboardState keyState = Keyboard.GetState();
- if (keyState.IsKeyDown(Keys.E))
- {
- this.Exit();
- }
- if (keyState.IsKeyDown(Keys.Up) || keyState.IsKeyDown(Keys.W))
- {
- //cameraPosition += new Vector3(0.0f, 50.0f, +100);
- angleUpDown += 0.05f;
- }
- if (keyState.IsKeyDown(Keys.Down) || keyState.IsKeyDown(Keys.S))
- {
- //cameraPosition -= new Vector3(0.0f, 50.0f, +100);wswdawds
- angleUpDown -= 0.05f;
- }
- if (keyState.IsKeyDown(Keys.Right) || keyState.IsKeyDown(Keys.D))
- {
- //cameraPosition += new Vector3(1, 0, 0);
- angleRightLeft += 0.05f;
- }
- if (keyState.IsKeyDown(Keys.Left) || keyState.IsKeyDown(Keys.A))
- {
- //cameraPosition += new Vector3(-1, 0, 0);
- angleRightLeft -= 0.05f;
- }
- if (keyState.IsKeyDown(Keys.Q))
- cameraPosition += new Vector3(0, 1, 0);
- if (keyState.IsKeyDown(Keys.Z))
- cameraPosition += new Vector3(0, -1, 0);
- if (keyState.IsKeyDown(Keys.Escape))
- {
- this.graphics.PreferredBackBufferWidth = 800;
- this.graphics.PreferredBackBufferHeight = 600;
- this.graphics.IsFullScreen = false;
- this.graphics.ApplyChanges();
- }
- if (this.graphics.PreferredBackBufferWidth < 1920)
- {
- /*if (WasMouseLeftClick())
- {
- changeScreenNode(this.graphics, 1920, 1080, true);
- }*/
- if (WasDoubleClick())
- {
- changeScreenNode(this.graphics, 1920, 1080, true);
- }
- }
- if (WasMouseLeftClick())
- {
- previousClick = DateTime.Now;
- }
- }
- private void changeScreenNode(GraphicsDeviceManager gdm , int width , int height , bool fullscreen)
- {
- gdm.PreferredBackBufferWidth = width;
- gdm.PreferredBackBufferHeight = height;
- gdm.IsFullScreen = fullscreen;
- gdm.ApplyChanges();
- }
- bool WasMouseLeftClick()
- {
- return (previousState.LeftButton == ButtonState.Pressed) && (currentState.LeftButton == ButtonState.Released);
- }
- bool WasDoubleClick()
- {
- return WasMouseLeftClick() // We have at least one click, and
- && (DateTime.Now - previousClick).TotalSeconds < MAXDELAY;
- }
- private void SetUpVertices()
- {
- // This part detect the minimum and maximum heights in our image. We will store these in the minHeight and maxHeight variables.
- vertices = new VertexPositionColorNormal[terrainWidth * terrainHeight];
- float minHeight = float.MaxValue;
- float maxHeight = float.MinValue;
- for (int x = 0; x < terrainWidth; x++)
- {
- for (int y = 0; y < terrainHeight; y++)
- {
- if (heightData[x, y] < minHeight)
- minHeight = heightData[x, y];
- if (heightData[x, y] > maxHeight)
- maxHeight = heightData[x, y];
- vertices[x + y * terrainWidth].Position = new Vector3(x, heightData[x, y], -y);
- if (heightData[x, y] < minHeight + (maxHeight - minHeight) / 4)
- vertices[x + y * terrainWidth].Color = Color.Blue;
- else if (heightData[x, y] < minHeight + (maxHeight - minHeight) * 2 / 4)
- vertices[x + y * terrainWidth].Color = Color.Green;
- else if (heightData[x, y] < minHeight + (maxHeight - minHeight) * 3 / 4)
- vertices[x + y * terrainWidth].Color = Color.Brown;
- else
- vertices[x + y * terrainWidth].Color = Color.White;
- }
- }
- // You check for each point of our grid if the current point’s height is below the current minHeight or above the current maxHeight. If it is, store the current height in the corresponding variable.
- // With these variables filled, you can specify the 4 regions of your colors
- /*vertices = new VertexPositionColor[terrainWidth * terrainHeight];
- for (int x = 0; x < terrainWidth; x++)
- {
- for (int y = 0; y < terrainHeight; y++)
- {
- vertices[x + y * terrainWidth].Position = new Vector3(x, heightData[x, y], -y);
- vertices[x + y * terrainWidth].Color = Color.White;
- }
- }*/
- }
- private void SetUpIndices()
- {
- indices = new int[(terrainWidth - 1) * (terrainHeight - 1) * 6];
- int counter = 0;
- for (int y = 0; y < terrainHeight - 1; y++)
- {
- for (int x = 0; x < terrainWidth - 1; x++)
- {
- int lowerLeft = x + y * terrainWidth;
- int lowerRight = (x + 1) + y * terrainWidth;
- int topLeft = x + (y + 1) * terrainWidth;
- int topRight = (x + 1) + (y + 1) * terrainWidth;
- indices[counter++] = topLeft;
- indices[counter++] = lowerRight;
- indices[counter++] = lowerLeft;
- indices[counter++] = topLeft;
- indices[counter++] = topRight;
- indices[counter++] = lowerRight;
- }
- }
- }
- private void LoadHeightData(Texture2D heightMap)
- {
- terrainWidth = heightMap.Width;
- terrainHeight = heightMap.Height;
- Color[] heightMapColors = new Color[terrainWidth * terrainHeight];
- heightMap.GetData(heightMapColors);
- heightData = new float[terrainWidth, terrainHeight];
- for (int x = 0; x < terrainWidth; x++)
- for (int y = 0; y < terrainHeight; y++)
- heightData[x, y] = heightMapColors[x + y * terrainWidth].R / 5.0f;
- }
- private void SetUpCamera()
- {
- viewMatrix = Matrix.CreateLookAt(new Vector3(60, 80, -80), new Vector3(0, 0, 0), new Vector3(0, 1, 0));
- projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, device.Viewport.AspectRatio, 1.0f, 300.0f);
- }
- private void CalculateNormals()
- {
- for (int i = 0; i < vertices.Length; i++)
- vertices[i].Normal = new Vector3(0, 0, 0);
- for (int i = 0; i < indices.Length / 3; i++)
- {
- int index1 = indices[i * 3];
- int index2 = indices[i * 3 + 1];
- int index3 = indices[i * 3 + 2];
- Vector3 side1 = vertices[index1].Position - vertices[index3].Position;
- Vector3 side2 = vertices[index1].Position - vertices[index2].Position;
- Vector3 normal = Vector3.Cross(side1, side2);
- vertices[index1].Normal += normal;
- vertices[index2].Normal += normal;
- vertices[index3].Normal += normal;
- }
- for (int i = 0; i < vertices.Length; i++)
- vertices[i].Normal.Normalize();
- }
- private void CopyToBuffers()
- {
- myVertexBuffer = new VertexBuffer(device, VertexPositionColorNormal.VertexDeclaration, vertices.Length, BufferUsage.WriteOnly);
- myVertexBuffer.SetData(vertices);
- myIndexBuffer = new IndexBuffer(device, typeof(int), indices.Length, BufferUsage.WriteOnly);
- myIndexBuffer.SetData(indices);
- }
- //*** Camera Part***\\
- private void ProcessInputCamera(float amount)
- {
- MouseState currentMouseState = Mouse.GetState();
- if (currentMouseState != originalMouseState)
- {
- float xDifference = currentMouseState.X - originalMouseState.X;
- float yDifference = currentMouseState.Y - originalMouseState.Y;
- leftrightRot -= rotationSpeed * xDifference * amount;
- updownRot -= rotationSpeed * yDifference * amount;
- Mouse.SetPosition(device.Viewport.Width / 2, device.Viewport.Height / 2);
- }
- Vector3 moveVector = new Vector3(0, 0, 0);
- KeyboardState keyState = Keyboard.GetState();
- if (keyState.IsKeyDown(Keys.Up) || keyState.IsKeyDown(Keys.W))
- moveVector += new Vector3(0, 0, -1);
- if (keyState.IsKeyDown(Keys.Down) || keyState.IsKeyDown(Keys.S))
- moveVector += new Vector3(0, 0, 1);
- if (keyState.IsKeyDown(Keys.Right) || keyState.IsKeyDown(Keys.D))
- moveVector += new Vector3(1, 0, 0);
- if (keyState.IsKeyDown(Keys.Left) || keyState.IsKeyDown(Keys.A))
- moveVector += new Vector3(-1, 0, 0);
- if (keyState.IsKeyDown(Keys.Q))
- moveVector += new Vector3(0, 1, 0);
- if (keyState.IsKeyDown(Keys.Z))
- moveVector += new Vector3(0, -1, 0);
- AddToCameraPosition(moveVector * amount);
- }
- private void AddToCameraPosition(Vector3 vectorToAdd)
- {
- Matrix cameraRotation = Matrix.CreateRotationX(updownRot) * Matrix.CreateRotationY(leftrightRot);
- Vector3 rotatedVector = Vector3.Transform(vectorToAdd, cameraRotation);
- cameraPosition += moveSpeed * rotatedVector;
- UpdateViewMatrix(viewMatrix);
- }
- private void UpdateViewMatrix(Matrix viewMatrix)
- {
- Matrix cameraRotation = Matrix.CreateRotationX(updownRot) * Matrix.CreateRotationY(leftrightRot);
- Vector3 cameraOriginalTarget = new Vector3(0, 0, -1);
- Vector3 cameraRotatedTarget = Vector3.Transform(cameraOriginalTarget, cameraRotation);
- Vector3 cameraFinalTarget = cameraPosition + cameraRotatedTarget;
- Vector3 cameraOriginalUpVector = new Vector3(0, 1, 0);
- Vector3 cameraRotatedUpVector = Vector3.Transform(cameraOriginalUpVector, cameraRotation);
- viewMatrix = Matrix.CreateLookAt(cameraPosition, cameraFinalTarget, cameraRotatedUpVector);
- }
- //************************************************************************************************\\
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement