Forum
Contact





DirectX using C#
DirectX using C++
DirectX using Visual Basic



Latest Forum posts

 Account settings
  Posted by: igthorn
  When: 21/04/2014 at 10:20:00

 Pavtube 2014 Easter Deals with 20% off
  Posted by: igthorn
  When: 21/04/2014 at 10:16:23

 20% off on iMedia Converter for Mac
  Posted by: VIKIVannessa
  When: 20/04/2014 at 01:35:54

 Pavtube Video Converter Ultimate Deal
  Posted by: VIKIVannessa
  When: 20/04/2014 at 01:35:50

 Easter Day Deals
  Posted by: Applefly
  When: 19/04/2014 at 22:18:14

 40% OFF Pavtube DVD Ripper for Mac
  Posted by: VIKIVannessa
  When: 19/04/2014 at 02:02:54

 DVD Ripper with 40% off
  Posted by: VIKIVannessa
  When: 19/04/2014 at 02:02:22

 Get DVD Ripper Wind/Mac + $14 Coupon
  Posted by: VIKIVannessa
  When: 19/04/2014 at 02:02:03

 Backup DVD Escape Plan
  Posted by: Applefly
  When: 17/04/2014 at 06:00:12

 Disney DVDs to MP4
  Posted by: Applefly
  When: 17/04/2014 at 05:56:07

 DVD movies through media streamer
  Posted by: VIKIVannessa
  When: 16/04/2014 at 02:25:09

 DVD movies to play on Galaxy Tab 3 10.1
  Posted by: VIKIVannessa
  When: 16/04/2014 at 02:20:51

 Blu-ray to Apple ProRes
  Posted by: Applefly
  When: 12/04/2014 at 00:47:46

 HD H.264 MP4 format
  Posted by: Applefly
  When: 12/04/2014 at 00:43:23

 DVD collection to computer
  Posted by: VIKIVannessa
  When: 04/04/2014 at 07:13:33

 DVD movies to play on Galaxy Tab 3 10.1
  Posted by: VIKIVannessa
  When: 04/04/2014 at 07:11:27

 DVD movies to play on Galaxy Tab 3 10.1
  Posted by: VIKIVannessa
  When: 04/04/2014 at 07:11:27

 DVD Ripper to populate
  Posted by: Applefly
  When: 04/04/2014 at 05:01:35

 kids and family watch DVD
  Posted by: Applefly
  When: 04/04/2014 at 04:59:21

 Blu-ray movie for your lovely kids
  Posted by: VIKIVannessa
  When: 02/04/2014 at 05:47:49




Topic: Refactored mess



  
Goto parent category
  
Create a new user account


   Refactored mess
 Poster : Armigus
 Posts: 34
 Country : USA
 City: WEston

  
Posted by Armigus on 08/02/2009 at 22:53:06
Game1.cs
using System;
using System.Collections.Generic;
using System.Linq;
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.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace ShowTerrain
{
    
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        Terrain land;
        Camera camera;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        protected override void Initialize()
        {
            graphics.PreferredBackBufferWidth = 1280;
            graphics.PreferredBackBufferHeight = 1024;

            graphics.ApplyChanges();
            Window.Title = "Riemer's XNA Tutorials -- Series 4";
            land = new Terrain();
            camera = new Camera();

            base.Initialize();
        }

        protected override void LoadContent()
        {
            camera.device = GraphicsDevice;

            camera.Setup(Content, MathHelper.PiOver4, 2000.0f);
            camera.Aim(new Vector3(130, 70, -50), MathHelper.PiOver2, -MathHelper.Pi / 10.0f);
            land.LoadContent(Content, camera.device);
            camera.sun = new Vector3(-0.5f, -1, -0.5f);
        }

        protected override void UnloadContent()
        {
        }

        protected override void Update(GameTime gameTime)
        {
            KeyboardState ks = Keyboard.GetState();
            if (ks.IsKeyDown(Keys.Escape)) this.Exit();

            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();
            float timeDifference = (float)gameTime.ElapsedGameTime.TotalMilliseconds / 1000.0f;
            camera.InputHandler(timeDifference);
            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            float time = (float)gameTime.TotalGameTime.TotalMilliseconds / 100.0f;
            
            land.Draw(camera);

            base.Draw(gameTime);
        }
    }
}

terrain.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace ShowTerrain
{
    public struct VertexPositionNormalColored
    {
        public Vector3 Position;
        public Color Color;
        public Vector3 Normal;

        public static int SizeInBytes = 7 * 4;
        public static VertexElement[] VertexElements = new VertexElement[]
              {
                  new VertexElement( 0, 0, VertexElementFormat.Vector3, VertexElementMethod.Default, VertexElementUsage.Position, 0 ),
                  new VertexElement( 0, sizeof(float) * 3, VertexElementFormat.Color, VertexElementMethod.Default, VertexElementUsage.Color, 0 ),
                  new VertexElement( 0, sizeof(float) * 4, VertexElementFormat.Vector3, VertexElementMethod.Default, VertexElementUsage.Normal, 0 ),
              };
    }

    public struct VertexMultitextured
    {
        public Vector3 Position;
        public Vector3 Normal;
        public Vector4 TextureCoordinate;
        public Vector4 TexWeights;

        public static int SizeInBytes = (3 + 3 + 4 + 4) * sizeof(float);
        public static VertexElement[] VertexElements = new VertexElement[]
     {
         new VertexElement( 0, 0, VertexElementFormat.Vector3, VertexElementMethod.Default, VertexElementUsage.Position, 0 ),
         new VertexElement( 0, sizeof(float) * 3, VertexElementFormat.Vector3, VertexElementMethod.Default, VertexElementUsage.Normal, 0 ),
         new VertexElement( 0, sizeof(float) * 6, VertexElementFormat.Vector4, VertexElementMethod.Default, VertexElementUsage.TextureCoordinate, 0 ),
         new VertexElement( 0, sizeof(float) * 10, VertexElementFormat.Vector4, VertexElementMethod.Default, VertexElementUsage.TextureCoordinate, 1 ),
     };
    }
    
    class Terrain : IDisposable
    {
        private string Name;
        private int Width;
        private int Length;
        private float[,] Altitudes;
        public Texture2D Map;
        private Texture2D[] Textures = new Texture2D[4];
        private VertexBuffer vBuffer;
        private IndexBuffer iBuffer;
        private VertexDeclaration vDeclaration;
        public Matrix location;
        public static float maxAlt = 30.0f;

        public Terrain()
        {
            Name = "heightmap";
        }

        public Terrain(string name)
        {
            Name = name;
        }

        public void Dispose() {}

        public void LoadContent(ContentManager cm, GraphicsDevice device)
        {
            location = Matrix.Identity;
            Map = cm.Load<Texture2D>("heightmap");
            Textures[0] = cm.Load<Texture2D>("sand");
            Textures[1] = cm.Load<Texture2D>("grass");
            Textures[2] = cm.Load<Texture2D>("rock");
            Textures[3] = cm.Load<Texture2D>("snow");
            LoadHeights();
            VertexMultitextured[] vertices = SetVertices();
            int[] indices = SetIndices();
            vertices = CalculateNormals(vertices, indices);
            SetBuffers(device, vertices, indices);
            vDeclaration = new VertexDeclaration(device, VertexMultitextured.VertexElements);
        }

        private void LoadHeights()
        {
            float minimumHeight = float.MaxValue;
            float maximumHeight = float.MinValue;

            Width = Map.Width;
            Length = Map.Height;

            Color[] heightMapColors = new Color[Width * Length];
            Map.GetData(heightMapColors);

            Altitudes = new float[Width, Length];
            for (int x = 0; x < Width; x++)
                for (int y = 0; y < Length; y++)
                {
                    Altitudes[x, y] = heightMapColors[x + y * Width].G * 256 + heightMapColors[x + y * Width].R;
                    if (Altitudes[x, y] < minimumHeight) minimumHeight = Altitudes[x, y];
                    if (Altitudes[x, y] > maximumHeight) maximumHeight = Altitudes[x, y];
                }

            for (int x = 0; x < Width; x++)
                for (int y = 0; y < Length; y++)
                    Altitudes[x, y] = (Altitudes[x, y] - minimumHeight) / (maximumHeight - minimumHeight) * maxAlt;
        }

        private VertexMultitextured[] SetVertices()
        {
            VertexMultitextured[] Vertices = new VertexMultitextured[Width * Length];

            for (int x = 0; x < Width; x++)
            {
                for (int y = 0; y < Length; y++)
                {
                    float x0, y0, z0, w0;
                    Vertices[x + y * Width].Position = new Vector3(x, Altitudes[x, y], -y);
                    Vertices[x + y * Width].TextureCoordinate.X = (float)x / maxAlt;
                    Vertices[x + y * Width].TextureCoordinate.Y = (float)y / maxAlt;
                    x0 = MathHelper.Clamp(1.0f - Math.Abs(Altitudes[x, y] / maxAlt - 0.0f) * 6, 0, 1);
                    y0 = MathHelper.Clamp(1.0f - Math.Abs(Altitudes[x, y] / maxAlt - 0.33f) * 5, 0, 1);
                    z0 = MathHelper.Clamp(1.0f - Math.Abs(Altitudes[x, y] / maxAlt - 0.67f) * 5, 0, 1);
                    w0 = MathHelper.Clamp(1.0f - Math.Abs(Altitudes[x, y] / maxAlt - 1.0f) * 5, 0, 1);
                    float isum = 1/(x0 + y0 + z0 + w0);
                    Vertices[x + y * Width].TexWeights.X = x0 * isum;
                    Vertices[x + y * Width].TexWeights.Y = y0 * isum;
                    Vertices[x + y * Width].TexWeights.Z = z0 * isum;
                    Vertices[x + y * Width].TexWeights.W = w0 * isum;
                }
            }
            
            return Vertices;
        }

        private int[] SetIndices()
        {
            int[] indices = new int[(Width - 1) * (Length - 1) * 6];
            int counter = 0;
            for (int y = 0; y < Length - 1; y++)
            {
                for (int x = 0; x < Width - 1; x++)
                {
                    int lowerLeft = x + y * Width;
                    int lowerRight = (x + 1) + y * Width;
                    int topLeft = x + (y + 1) * Width;
                    int topRight = (x + 1) + (y + 1) * Width;

                    indices[counter++] = topLeft;
                    indices[counter++] = lowerRight;
                    indices[counter++] = lowerLeft;

                    indices[counter++] = topLeft;
                    indices[counter++] = topRight;
                    indices[counter++] = lowerRight;
                }
            }

            return indices;
        }

        private VertexMultitextured[] CalculateNormals(VertexMultitextured[] vertices, int[] indices)
        {
            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();

            return vertices;
        }

        private void SetBuffers(GraphicsDevice device, VertexMultitextured[] vertices, int[] indices)
        {
            vBuffer = new VertexBuffer(device, vertices.Length * VertexMultitextured.SizeInBytes, BufferUsage.WriteOnly);
            vBuffer.SetData(vertices);

            iBuffer = new IndexBuffer(device, typeof(int), indices.Length, BufferUsage.WriteOnly);
            iBuffer.SetData(indices);
        }

        public void Draw(Camera camera)
        {
            camera.Snap(Matrix.Identity);
            camera.SetTexture("xTexture0", Textures[0]);
            camera.SetTexture("xTexture1", Textures[1]);
            camera.SetTexture("xTexture2", Textures[2]);
            camera.SetTexture("xTexture3", Textures[3]);

            camera.Begin();
            foreach (EffectPass pass in camera.CurrentTechnique().Passes)
            {
                pass.Begin();

                camera.device.Vertices[0].SetSource(vBuffer, 0, VertexMultitextured.SizeInBytes);
                camera.device.Indices = iBuffer;
                camera.device.VertexDeclaration = vDeclaration;

                int noVertices = vBuffer.SizeInBytes / VertexMultitextured.SizeInBytes;
                int noTriangles = iBuffer.SizeInBytes / sizeof(int) / 3;
                camera.device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, noVertices, 0, noTriangles);

                pass.End();
            }
            camera.End();
        }
    }
}

camera.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace ShowTerrain
{
    class Camera
    {
        private Matrix view;
        private Matrix projection;
        private Effect fx;
        public GraphicsDevice device;
        public Vector3 sun;
        public Vector3 location;
        public float longitude;
        public float latitude;
        static float angVelocity = 0.3f;
        static float moveVelocity = 30.0f;
        static string source = "Series4Effects";
        MouseState mouse;

        public Camera()
        {
        }

        public void Setup(ContentManager cm, float angle, float distance)
        {
            fx = cm.Load<Effect>(source);
            projection = Matrix.CreatePerspectiveFieldOfView(angle, device.Viewport.AspectRatio, 0.3f, distance);
            Mouse.SetPosition(device.Viewport.Width / 2, device.Viewport.Height / 2);
            mouse = Mouse.GetState();
        }

        public void Aim(Vector3 pos, float lng, float lat)
        {
            location = pos;
            longitude = lng;
            latitude = lat;
            Update();
        }

        public void SetTexture(string name, Texture2D tex) {
            fx.Parameters[name].SetValue(tex);
        }

        public void Begin()
        {
            fx.Begin();
        }

        public void End()
        {
            fx.End();
        }

        public EffectTechnique CurrentTechnique()
        {
            return fx.CurrentTechnique;
        }

        public void Snap(Matrix world)
        {
            device.RenderState.CullMode = CullMode.None;

            device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1.0f, 0);
            fx.CurrentTechnique = fx.Techniques["Textured"];
            fx.Parameters["xWorld"].SetValue(world);
            fx.Parameters["xView"].SetValue(view);
            fx.Parameters["xProjection"].SetValue(projection);

            fx.Parameters["xEnableLighting"].SetValue(true);
            fx.Parameters["xAmbient"].SetValue(0.4f);
            fx.Parameters["xLightDirection"].SetValue(sun);
        }

        public void InputHandler(float time)
        {
            bool Dirty = false; // Do we need to update?
            MouseState newMouse = Mouse.GetState();
            if (newMouse != mouse)
            {
                Dirty = true;
                float dx = newMouse.X - mouse.X;
                float dy = newMouse.Y - mouse.Y;
                longitude -= angVelocity * dx * time;
                latitude -= angVelocity * dy * time;
                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);
            if (moveVector.Length() > 0.0f)
            {
                Dirty = true;
                moveVector *= time;
                Matrix aimold = Matrix.CreateRotationX(latitude) * Matrix.CreateRotationY(longitude);
                Vector3 direction = Vector3.Transform(moveVector, aimold);
                location += moveVelocity * direction;
            }
            if (Dirty) Update();
        }

        private void Update()
        {
            Matrix cameraRotation = Matrix.CreateRotationX(latitude) * Matrix.CreateRotationY(longitude);
            Vector3 target = Vector3.Transform(Vector3.Forward, cameraRotation)+location;
            Vector3 up = Vector3.Transform(Vector3.Up, cameraRotation);
            view = Matrix.CreateLookAt(location, target, up);
        }
    }
}

Everything compiles and runs, but all I get is a black screen.  Can someone point out my error?
 Poster : Armigus
 Posts: 34
 Country : USA
 City: WEston

  
Posted by Armigus on 08/02/2009 at 23:55:46
Ha,ha.  I hadn't changed the technique:

fx.CurrentTechnique = fx.Techniques["MultiTextured"];

  
Post a new reply
 





Google
 
Web www.riemers.net
If you appreciate the amount of time I spend creating and updating
these pages, feel free to donate -- any amount is welcome !
- Website design & DirectX code : Riemer Grootjans -
©2006 Riemer Grootjans


News
Home
Forum
XNA 2.0 Recipes Book (8)
XNA 3.0 Recipes Book (8)
Downloads
Extra Reading (3)
Matrices: geometrical
Matrix Mathematics
Homogenous matrices
Community Projects (1)
Tutorials (160)
XNA 4.0 using C# (89)
DirectX using C# (54)
Series 1:Terrain (14)
Opening a window
Linking to the Device
Drawing a triangle
Camera
Rotation - Translation
Indices
Terrain creation
Terrain from file
DirectInput
Importing bmp files
Colored vertices
DirectX Light basics
Mesh creation
Mesh lighting
Series 2: Flightsim (19)
Series 3: HLSL (19)
Short Tuts (2)
Resizing problem
Checking Device caps
DirectX using C++ (15)
DirectX using VB (2)