XNA for C#
DirectX 9 for C#
DirectX 9 for C++
DirectX 9 for VB
Forum
   August 19: 2D - Chapter 3 posted
My Book: Out Now!
      
       Go to section on this site

Additional info


Latest Forum posts

 BSP Tree Tutorial
  Posted by: lbmurali
  When: 21/08/2008 at 13:41:47

 Loading compiled .xnb files
  Posted by: lbmurali
  When: 21/08/2008 at 13:33:00

 The city isn't very detailed and....
  Posted by: dom96
  When: 21/08/2008 at 12:52:47

 Height-map, low framerate
  Posted by: Rich_Zap
  When: 21/08/2008 at 11:45:00

 Vertex and Index
  Posted by: radulph
  When: 21/08/2008 at 08:33:06

 The city isn't very detailed and....
  Posted by: radulph
  When: 21/08/2008 at 08:26:03

 Vertex and Index
  Posted by: engine
  When: 21/08/2008 at 06:11:35

 What about Joypad Control
  Posted by: greyrat
  When: 20/08/2008 at 22:19:13

 The city isn't very detailed and....
  Posted by: radulph
  When: 20/08/2008 at 17:20:00

 I have a problem(with camera i think)
  Posted by: vToMy
  When: 20/08/2008 at 16:25:45


Ads

Sunrise over your terrain

Finally, we have reached the chapter where we actually put some light on our terrain. Last chapter we’ve melded both our vertices and indices together in a new structure, the Mesh. Now it’s time to see another benefit of this Mesh structure: DirectX can automatically calculate the normal vectors in the vertices of our Mesh. First, we are going to replace our Mesh with a Mesh that supports the PositionNormalColored vertexformat. We can easily do this using the handy Clone method, so simply put these lines at the bottom of your CreateMesh method:

  meshTerrain = meshTerrain.Clone(meshTerrain.Options.Value, CustomVertex.PositionNormalColored.Format, device);
 meshTerrain.ComputeNormals();

 The first line ‘clones’ the original Mesh to a Mesh with the PositionNormalColored vertexformat. The first argument simply copies the Options from the original Mesh to the new one. In the end, we also have to pass the device. The second line simply completes the huge task of calculating all the normal vectors we need!
 
This Mesh, completed with normal vectors, can be used by DirectX to calculate the amount of light (or shadow!) that hits every vertex, such as explained 2 chapters ago.
 
When you run this code, you’ll notice that not so much has changed!! You guessed it, we didn’t yet tell DirectX to use lights yet! So go to the part where you define your camera position and stuff, and add the following lines:

 device.RenderState.Lighting = true;
  
 device.Lights[0].Type = LightType.Directional;
 device.Lights[0].Diffuse = Color.White;
 device.Lights[0].Direction = new Vector3(-0.5f, 0, -1f);
 device.Lights[0].Enabled = true;

 The first line tells DirectX we are going to use lights (so it will need the normal data we supply). Then we define the actual light: a simple directional white light. Now run this code! You should see the following:




DirectX Tutorial 14 - Mesh lighting

If you appreciate the amount of time I spend creating and updating
these pages, feel free to donate -- any amount is welcome !



Click here to go to the forum on this chapter!

Or click on one of the topics on this chapter to go there:
  • Rotating the object...
          When you rotate the world matrix, it looks like yo...
  • Black Screen
          I had a minor problem with the last tutorial but I...
  • Regarding WIDTH and HEIGHT
          I really love using the mesh object to compute the...
  • Let there be... dark
          First i'd like to thank you for the nicely done t...
  • Culling
          Hello, What sort of culling should we use in a...
  • Direction of lights
          Hi, I've started a 'own' project and wanted ...



      You have reached the final chapter of this series of tutorials. Every chapter you learned a basic DirectX skill. Starting from linking to your graphics card, you’ve written a program that reads a .bmp file and converts its contents to a 3D terrain. This would be an excellent moment to further experiment with several settings, such as the camera position and so on. Have fun!

    The final code:

     using System;
     using System.Drawing;
     using System.Collections;
     using System.ComponentModel;
     using System.Windows.Forms;
     using System.Data;
     using Microsoft.DirectX;
     using Microsoft.DirectX.Direct3D;
     using System.IO;
     using Microsoft.DirectX.DirectInput;
     
     namespace DirectX_Tutorial
     {
         public class WinForm : System.Windows.Forms.Form
         {
             private int WIDTH = 64;
             private int HEIGHT = 64;
             private Microsoft.DirectX.Direct3D.Device device;
             private System.ComponentModel.Container components = null;
             private float angle = 0f;
             private CustomVertex.PositionColored[] vertices;
             private int[,] heightData;
             private short[] indices;
             private Microsoft.DirectX.DirectInput.Device keyb;
             private int MinimumHeight = 255;
             private int MaximumHeight = 0;
             private Mesh meshTerrain;
     
             public WinForm()
             {
                 InitializeComponent();
                 this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true);
             }
     
             public void InitializeDevice()
             {
                 PresentParameters presentParams = new PresentParameters();
                 presentParams.Windowed = true;
                 presentParams.SwapEffect = SwapEffect.Discard;
                 presentParams.AutoDepthStencilFormat = DepthFormat.D16;
                 presentParams.EnableAutoDepthStencil = true;
                 device = new Microsoft.DirectX.Direct3D.Device(0, Microsoft.DirectX.Direct3D.DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, presentParams);
             }
     
             public void InitializeKeyboard()
             {
                 keyb = new Microsoft.DirectX.DirectInput.Device(SystemGuid.Keyboard);
                 keyb.SetCooperativeLevel(this, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);
                 keyb.Acquire();
             }
     
             private void CameraPositioning()
             {
                 device.Transform.Projection = Matrix.PerspectiveFovLH((float)Math.PI / 4, this.Width / this.Height, 1f, 250f);
                 device.Transform.View = Matrix.LookAtLH(new Vector3(80, 0, 120), new Vector3(-20, 0, 0), new Vector3(0, 0, 1));
                 device.RenderState.CullMode = Cull.None;
                 device.RenderState.Lighting = true;
     
                 device.Lights[0].Type = LightType.Directional;
                 device.Lights[0].Diffuse = Color.White;
                 device.Lights[0].Direction = new Vector3(-0.5f, 0, -1f);
                 device.Lights[0].Enabled = true;
             }
     
             private void VertexDeclaration()
             {
                 vertices = new CustomVertex.PositionColored[WIDTH*HEIGHT];

                for (int x=0;x< WIDTH;x++)            {

                    for (int y=0; y< HEIGHT;y++)                {
                        vertices[x + y * WIDTH].Position = new Vector3(x, y, heightData[x,y]);
                        if (heightData[x, y] < MinimumHeight + (MaximumHeight - MinimumHeight) / 4)
                        {
                            vertices[x + y * WIDTH].Color = Color.Blue.ToArgb();
                        }
                        else if (heightData[x, y] < MinimumHeight + (MaximumHeight - MinimumHeight) * 2 / 4)
                        {
                            vertices[x + y * WIDTH].Color = Color.Green.ToArgb();
                        }
                        else if (heightData[x, y] < MinimumHeight + (MaximumHeight - MinimumHeight) * 3 / 4)
                        {
                            vertices[x + y * WIDTH].Color = Color.Brown.ToArgb();
                        }
                        else
                        {
                            vertices[x + y * WIDTH].Color = Color.White.ToArgb();
                        }
                    }
                }
            }

            private void IndicesDeclaration()
            {
                indices = new short[(WIDTH-1)*(HEIGHT-1)*6];

                for (int x=0;x< WIDTH-1;x++)            {

                    for (int y=0; y< HEIGHT-1;y++)                {
                        indices[(x + y * (WIDTH - 1)) * 6] = (short)(x + y * WIDTH);
                        indices[(x + y * (WIDTH - 1)) * 6 + 1] = (short)((x + 1) + y * WIDTH);
                        indices[(x + y * (WIDTH - 1)) * 6 + 2] = (short)((x + 1) + (y + 1) * WIDTH);

                        indices[(x + y * (WIDTH - 1)) * 6 + 3] = (short)(x + (y + 1) * WIDTH);
                        indices[(x + y * (WIDTH - 1)) * 6 + 4] = (short)(x + y * WIDTH);
                        indices[(x + y * (WIDTH - 1)) * 6 + 5] = (short)((x + 1) + (y + 1) * WIDTH);
                    }
                }
            }

            protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
            {
                device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
                device.BeginScene();

                device.Transform.World = Matrix.Translation(-HEIGHT / 2, -WIDTH / 2, 0) * Matrix.RotationZ(angle);

                int numSubSets = meshTerrain.GetAttributeTable().Length;
                for (int i = 0; i < numSubSets; ++i)
                {
                    meshTerrain.DrawSubset(i);
                }

                device.EndScene();
                device.Present();
                this.Invalidate();
                ReadKeyboard();
            }

            private void ReadKeyboard()
            {
                KeyboardState keys = keyb.GetCurrentKeyboardState();
                if (keys[Key.Delete])
                {
                    angle+=0.03f;
                }
                if (keys[Key.Next])
                {
                    angle-=0.03f;
                }
            }

            private void LoadHeightData()
            {
                int offset;
                byte dummy;

                FileStream fs = new FileStream("heightmap.bmp", FileMode.Open, FileAccess.Read);
                BinaryReader r = new BinaryReader(fs);

                for (int i = 0; i < 10; i++)
                {
                    dummy = r.ReadByte();
                }

                offset = r.ReadByte();
                offset += r.ReadByte() * 256;
                offset += r.ReadByte() * 256 * 256;
                offset += r.ReadByte() * 256 * 256 * 256;

                for (int i = 0; i < 4; i++)
                {
                    dummy = r.ReadByte();
                }

                WIDTH = r.ReadByte();
                WIDTH += r.ReadByte() * 256;
                WIDTH += r.ReadByte() * 256 * 256;
                WIDTH += r.ReadByte() * 256 * 256 * 256;

                HEIGHT = r.ReadByte();
                HEIGHT += r.ReadByte() * 256;
                HEIGHT += r.ReadByte() * 256 * 256;
                HEIGHT += r.ReadByte() * 256 * 256 * 256;

                heightData = new int[WIDTH, HEIGHT];
                for (int i = 0; i < (offset - 26); i++)
                {
                    dummy = r.ReadByte();
                }

                for (int i = 0; i < HEIGHT; i++)
                {
                    for (int y = 0; y < WIDTH; y++)
                    {
                        int height = (int)(r.ReadByte());
                        height += (int)(r.ReadByte());
                        height += (int)(r.ReadByte());
                        height /= 8;
                        heightData[WIDTH - 1 - y, HEIGHT - 1 - i] = height;
                        if (height < MinimumHeight)
                        {
                            MinimumHeight = height;
                        }
                        if (height > MaximumHeight)
                        {
                            MaximumHeight = height;
                        }
                    }
                }
            }

            private void CreateMesh()
            {
                meshTerrain = new Mesh((WIDTH - 1) * (HEIGHT - 1) * 2, WIDTH * HEIGHT, MeshFlags.Managed, CustomVertex.PositionColored.Format, device);

                meshTerrain.SetVertexBufferData(vertices, LockFlags.None);
                meshTerrain.SetIndexBufferData(indices, LockFlags.None);

                int[] adjac = new int[meshTerrain.NumberFaces * 3];
                meshTerrain.GenerateAdjacency(0.5f, adjac);
                meshTerrain.OptimizeInPlace(MeshFlags.OptimizeVertexCache, adjac);


                 meshTerrain = meshTerrain.Clone(meshTerrain.Options.Value, CustomVertex.PositionNormalColored.Format, device);
                 meshTerrain.ComputeNormals();
             }
     
             protected override void Dispose (bool disposing)
             {
                 if (disposing)
                 {
                     if (components != null)
                     {
                         components.Dispose();
                     }
                 }
                 base.Dispose(disposing);
             }
     
             private void InitializeComponent()
             {
                 this.components = new System.ComponentModel.Container();
                 this.Size = new System.Drawing.Size(500,500);
                 this.Text = "DirectX Tutorial";
             }
     
             static void Main()
             {
                 using (WinForm our_directx_form = new WinForm())
                 {
                     our_directx_form.LoadHeightData();
                     our_directx_form.InitializeDevice();
                     our_directx_form.CameraPositioning();
                     our_directx_form.VertexDeclaration();
                     our_directx_form.IndicesDeclaration();
                     our_directx_form.CreateMesh();
                     our_directx_form.InitializeKeyboard();
                     our_directx_form.Show();
                     Application.Run(our_directx_form);
                 }
             }
         }
     }
     
     


    Google
     
    Webwww.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 & XNA + DirectX code : Riemer Grootjans -
    ©2003 - 2008 Riemer Grootjans
  • Translations

    This site in English
    This site in Korean
    This site in Czech

    Microsoft MVP Award



    2007 - 2008 MVP Award
    DirectX - XNA

    Contents

    News
    Home
    Forum
    XNA 2.0 Recipes Book (8)
    Downloads
    Extra Reading (3)
    Matrices: geometrical
    Matrix Mathematics
    Homogenous matrices
    Tutorials (141)
    XNA 2.0 using C# (70)
    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)
    DirectX using C++ (15)
    DirectX using VB (2)
    -- Expand all --


    Thank you!

    Support this site --
    any amount is welcome !

    Stay up-to-date

    I don't have the time to keep a News section, so stay informed about the updates by clicking on this RSS file!