XNA for C#
DirectX 9 for C#
DirectX 9 for C++
DirectX 9 for VB
Forum
   
My XNA Book
      
       Go to section on this site

Additional info


Latest Forum posts

 Account settings
  Posted by: Anonymous
  When: 07/05/2014 at 09:48:39

 forced subtitle
  Posted by: Applefly
  When: 07/05/2014 at 06:00:48

 convert DVD into PMS
  Posted by: Applefly
  When: 07/05/2014 at 05:55:25

 DVD to Digital Copy easily
  Posted by: VIKIVannessa
  When: 05/05/2014 at 06:52:29

 DVD on Xbox 360/Xbox One Console
  Posted by: VIKIVannessa
  When: 05/05/2014 at 06:51:47

 Extract .Srt Subtitles
  Posted by: Applefly
  When: 04/05/2014 at 03:54:38

 Encode Movie collection
  Posted by: Applefly
  When: 04/05/2014 at 03:52:41

 Convert DVD to WMV
  Posted by: Applefly
  When: 29/04/2014 at 05:53:50

 rip DVDs into digital files
  Posted by: Applefly
  When: 29/04/2014 at 05:51:20

 iTunes movies/music to Kindle Fire
  Posted by: ciciyu80
  When: 29/04/2014 at 05:10:20


Ads

World transformation

This chapter will be quite easy for people that are good in maths. In HLSL, you have to perform all transformations yourself. To give all people the possibility of completely understanding what they’re doing in this 3rd Series, I’ve decided to write this extra chapter.

We’ll be drawing the cars and lampposts from 2 meshes, so you would like to add these variables:

 private Mesh Lamppost;
 private Material[] LamppostMaterials;
 private Texture[] LamppostTextures;
 private Mesh Car;
 private Material[] CarMaterials;
 private Texture[] CarTextures;

Next we need to fill these resources, so put these lines in the FillResources method:

 LoadMesh("lamppost.x", ref Lamppost, ref LamppostMaterials, ref LamppostTextures);
 LoadMesh("car.x", ref Car, ref CarMaterials, ref CarTextures);

You can download both meshes here and here.

The next step would simply be to draw the meshes. But don’t we first have to set the World transform ?

Remember when the World transform is used? Whenever you want to draw some triangles (from a vertex buffer or from a mesh), you have to set the world transform first. If you wouldn’t, all triangles would be drawn relative to the origin, the (0,0,0) point.

Imagine you want to draw 2 objects from the same mesh, like our 2 lampposts. If you wouldn’t set a different world transform before drawing them, both objects would be drawn at the same place, so you would see only one of them. What you would rather like to do, is tell DirectX to draw the first object ‘3 units to the left and 2 units up’, and draw the second object ‘3 units to the right and rotated around the Y axis for 40 degrees and twice as big as the first one’. This ‘transformation’ is called the World transform, and is stored in a matrix. For more info on matrices, what they look like and what you can do with them, you can check out the matrix entries in the Extra Reading section.

Something like the example above is displayed in the image below: the big axes represent our World axes, with its origin in the World (0,0,0) point. Say you would like to draw the first object from a mesh. First, you would have to tell DirectX to create a new axis, with origin where you would like the center of the object to be drawn. This new location, as well as its rotation and its scaling, are stored in a matrix M1. When you draw your mesh, the mesh will be drawn around the new axis.



The same story for the second object: you first have to set M2 as World transform, to object 2 will be drawn around the correct axis.

Using the Fixed-Function Pipeline, we just had to call device.Transform.World = M1;. Now, using the Programmable Pipeline, we have to multiply our vertices with this World matrix in our vertex shader.

The correct order of multiplication would be: World, View and then Projection. We will perform this multiplication in our DirectX app, so we need to perform only the multiplication of our vertices with this combined matrix in our vertex shader. So go to your .fx file, and change all instances of xViewProjection to xWorldViewProjection:

float4x4 xWorldViewProjection;

And

Output.Position = mul(inPos, xWorldViewProjection);

The first line means HLSL expects the DirectX app to fill this matrix, and the second line multiplies every vertex with this combined matrix. The result is that every vertex is first transformed to its proper local axis, and then transformed to 2D screen coordinates!

Now we still need to fill this matrix. Go to the OnPaint method in your DirectX code, and replace the line where you fill the xViewProjection matrix by this line:

 effect.SetValue("xWorldViewProjection", Matrix.Identity * matView * matProjection);

Because our TriangleStrip actually needs to be drawn around the World origin, we don’t need a World matrix. In that case, you can specify Matrix.Identity, which is the unity element in matrix maths: multiplying matrix M by the identity matrix gives M.

When you run this code, you should see exactly the same as last chapter, which is OK. Now we’re going to add the first lamppost. For this we’re going to use the same effect, so put this between your calls to effect.BeginPass and effect.EndPass:

 Matrix LamppostWorld = Matrix.Scaling(0.05f, 0.05f, 0.05f) * Matrix.RotationX((float)Math.PI / 2) * Matrix.Translation(-4.0f, 5, 1);
 effect.SetValue("xWorldViewProjection", LamppostWorld * matView * matProjection);
 effect.CommitChanges();
 DrawMesh(Lamppost, LamppostMaterials, LamppostTextures);

The first line defines the World matrix for the first lamp post. First, the axis is scaled, so the mesh will nicely fit into our scene. Then, it is rotated so it is correctly positioned. Lastly, the axis is translated to its proper spot.

These changes are only updated in your effect after a call to CommitChanges (or to effect.Begin). When everything is OK, we finally draw our mesh.

When you run the code, you’ll see your first lamppost. It doesn’t look that nice, which is because it isn’t lit correctly yet, and it doesn’t shine any light yet as well. Let’s first add the second lamppost, as well as both cars:

 LamppostWorld = Matrix.Scaling(0.05f, 0.05f, 0.05f) * Matrix.RotationX((float)Math.PI / 2) * Matrix.Translation(-4.0f, 35, 1);
 effect.SetValue("xWorldViewProjection", LamppostWorld * matView * matProjection);
 effect.CommitChanges();
 DrawMesh(Lamppost, LamppostMaterials, LamppostTextures);
 
 Matrix CarWorld = Matrix.Scaling(4f, 4f, 4f) * Matrix.RotationYawPitchRoll((float)Math.PI / 2, (float)Math.PI / 2, (float)Math.PI / 2) * Matrix.Translation(3, 15, 0f);
 effect.SetValue("xWorldViewProjection", CarWorld * matView * matProjection);
 effect.CommitChanges();
 DrawMesh(Car, CarMaterials, CarTextures);
 
 CarWorld = Matrix.Scaling(4f, 4f, 4f) * Matrix.RotationYawPitchRoll((float)Math.PI / 2, (float)Math.PI / 8, (float)Math.PI / 2) * Matrix.Translation(28, -1.9f, 0f);
 effect.SetValue("xWorldViewProjection", CarWorld * matView * matProjection);
 effect.CommitChanges();
 DrawMesh(Car, CarMaterials, CarTextures);

This should already give you the final image of this chapter. However, to do everything the HLSL way, there’s still one line we need to update: the one that sets the texture of the meshes. When you have a look at the DrawMesh method, you’ll see that the first line is a bit of a hack. Our lamppost doesn’t have any textures, so that line checks if the current mesh has textures. For the lamppost, this if check will fail, so the streetmesh.jpg is used to texture the lampposts (hence the brown color of the lampposts). For our car, however, we need to set the correct textures. Up to this moment, we’re using the FFP function device.SetTexture, which should of course be replaced by this line:

 if (meshtextures.Length > 3) effect.SetValue("xColoredTexture", meshtextures[i]);
 effect.CommitChanges();

Because we’re changing a HLSL parameter, we need to recommit our changed. For a bit better performance, you can drop the last 4 calls to CommitChanges from within your DrawScene method, as they are being followed by a call to DrawMesh, which automatically updates the HLSL variables.




DirectX Tutorial 8 - World transform

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:
  • meshtextures exception
          Hi. I had some problems with meshtextures[i] = ...
  • Black
          When I run it. I get the tiny little car and with ...
  • Cant undestand your example picture
          Sorry for bothering you ppl, but i got a problem w...
  • Direct3DXException
          I have got a problem when I tried to compile the c...
  • Model pivot point
          Hi, I have this problem when I place the car mo...
  • mesh download
          Hi Riemer, sorry, but when I try to download yo...


    The scene looks a bit dull, because only ambient lighing has been used. In the next chapter, we’ll be adding normals to our vertices. These are needed before we can move on to our first light!

    The HLSL code:

    struct VertexToPixel
    {
        float4 Position     : POSITION;
        float2 TexCoords    : TEXCOORD0;
    };

    struct PixelToFrame
    {
        float4 Color : COLOR0;
    };


     float4x4 xWorldViewProjection;


    Texture xColoredTexture;

    sampler ColoredTextureSampler = sampler_state { texture = <xColoredTexture> ; magfilter = LINEAR; minfilter = LINEAR; mipfilter=LINEAR; AddressU = mirror; AddressV = mirror;};
    VertexToPixel SimplestVertexShader( float4 inPos : POSITION, float2 inTexCoords : TEXCOORD0)
    {
        VertexToPixel Output = (VertexToPixel)0;
        

         Output.Position = mul(inPos, xWorldViewProjection);

        Output.TexCoords = inTexCoords;
        
        return Output;    
    }

    PixelToFrame OurFirstPixelShader(VertexToPixel PSIn)
    {
        PixelToFrame Output = (PixelToFrame)0;

        Output.Color = tex2D(ColoredTextureSampler, PSIn.TexCoords);

        return Output;
    }

    technique Simplest
    {
        pass Pass0
        {
            VertexShader = compile vs_1_1 SimplestVertexShader();
            PixelShader = compile ps_1_1 OurFirstPixelShader();
        }
    }

    And the DirectX 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 D3D = Microsoft.DirectX.Direct3D;
     
     namespace DirectX_Tutorial
     {
         struct myownvertexformat
         {
             public Vector3 Pos;
             public Vector2 TexCoord;
     
             public myownvertexformat(Vector3 _Pos, float texx, float texy)
             {
                 Pos = _Pos;
                 TexCoord.X = texx;
                 TexCoord.Y = texy;
             }
         }
     
         public class WinForm : System.Windows.Forms.Form
         {        
             private System.ComponentModel.Container components = null;
             private D3D.Device device;        
             private VertexBuffer vb;
             private Vector3 CameraPos;
             private VertexDeclaration vd;
             private Effect effect;
     
             private Texture StreetTexture;
             private Mesh Lamppost;
             private Material[] LamppostMaterials;
             private Texture[] LamppostTextures;
             private Mesh Car;
             private Material[] CarMaterials;
             private Texture[] CarTextures;
     
             private Matrix matView;
             private Matrix matProjection;
     
             private int LastTickCount = 1;
             private int Frames = 0;
             private float LastFrameRate = 0;
             private D3D.Font text;
     
             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;
     
                 Caps DevCaps = D3D.Manager.GetDeviceCaps(0, D3D.DeviceType.Hardware);
                 D3D.DeviceType DevType = D3D.DeviceType.Reference;
                 CreateFlags DevFlags = CreateFlags.SoftwareVertexProcessing;
                 if ((DevCaps.VertexShaderVersion >= new Version(2, 0)) && (DevCaps.PixelShaderVersion >= new Version(2, 0)))
                 {
                     DevType = D3D.DeviceType.Hardware;                
                     if (DevCaps.DeviceCaps.SupportsHardwareTransformAndLight)
                     {
                         DevFlags = CreateFlags.HardwareVertexProcessing;
                         if (DevCaps.DeviceCaps.SupportsPureDevice)
                         {
                             DevFlags |= CreateFlags.PureDevice;
                         }
                     }                
                 }
     
                 device = new D3D.Device(0, DevType, this, DevFlags, presentParams);
                 device.DeviceReset += new EventHandler(this.HandleDeviceReset);            
             }
     
             private void HandleDeviceReset(object sender, EventArgs e)
             {
                 FillResources();        
             }
     
             private void AllocateResources()
             {
                 vb = new VertexBuffer(typeof(myownvertexformat), 12, device, Usage.WriteOnly, VertexFormats.Position | VertexFormats.Normal | VertexFormats.Texture0, Pool.Managed);                        
                 InitializeFont();
                 effect = D3D.Effect.FromFile(device, @"../../OurHLSLFile.fx", null, null, ShaderFlags.None, null);
             }
     
             private void FillResources()
             {
                 myownvertexformat[] vertices = new myownvertexformat[12];
     
                 vertices[0] = new myownvertexformat(new Vector3(20, -10, 0), -0.25f, 25.0f);
                 vertices[1] = new myownvertexformat(new Vector3(20, 100, 0), -0.25f, 0.0f);
                 vertices[2] = new myownvertexformat(new Vector3(-2, -10, 0), 0.25f, 25.0f);                        
                 vertices[3] = new myownvertexformat(new Vector3(-2, 100, 0), 0.25f, 0.0f);
                 vertices[4] = new myownvertexformat(new Vector3(-2, -10, 1), 0.375f, 25.0f);
                 vertices[5] = new myownvertexformat(new Vector3(-2, 100, 1), 0.375f, 0.0f);
                 vertices[6] = new myownvertexformat(new Vector3(-3, -10, 1), 0.5f, 25.0f);
                 vertices[7] = new myownvertexformat(new Vector3(-3, 100, 1), 0.5f, 0.0f);
                 vertices[8] = new myownvertexformat(new Vector3(-13, -10, 1), 0.75f, 25.0f);
                 vertices[9] = new myownvertexformat(new Vector3(-13, 100, 1), 0.75f, 0.0f);
                 vertices[10] = new myownvertexformat(new Vector3(-13, -10, 21), 1.25f, 25.0f);
                 vertices[11] = new myownvertexformat(new Vector3(-13, 100, 21), 1.25f, 0.0f);
                 
                 vb.SetData(vertices, 0, LockFlags.None);
     
                 SetUpCamera();
     
                 VertexElement[] velements = new VertexElement[]
                 {
                     new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0),
                     new VertexElement(0, 12, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0),
                     VertexElement.VertexDeclarationEnd
                 };
                 vd = new VertexDeclaration(device, velements);
     
                 StreetTexture = TextureLoader.FromFile(device, "streettexture.jpg");
     
                 LoadMesh("lamppost.x", ref Lamppost, ref LamppostMaterials, ref LamppostTextures);
                 LoadMesh("car.x", ref Car, ref CarMaterials, ref CarTextures);
             }
     
             private void InitializeFont()
             {
                 System.Drawing.Font systemfont = new System.Drawing.Font("Arial", 12f, FontStyle.Regular);
                 text = new D3D.Font(device, systemfont);
             }
     
             private void DrawMesh(Mesh mesh, Material[] meshmaterials, Texture[] meshtextures)
             {
                 for (int i = 0; i < meshmaterials.Length; i++)
                 {
                     if (meshtextures.Length > 3) effect.SetValue("xColoredTexture", meshtextures[i]);
                     effect.CommitChanges();
                     mesh.DrawSubset(i);
                 }
             }
     
             protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
             {
                 device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
                 device.BeginScene();
     
                 device.SetStreamSource(0, vb, 0);            
                 device.VertexDeclaration = vd;
                 effect.Technique = "Simplest";
                 effect.SetValue("xWorldViewProjection", Matrix.Identity * matView * matProjection);
                 effect.SetValue("xColoredTexture", StreetTexture);
                 int numpasses = effect.Begin(0);
                 for (int i = 0; i < numpasses; i++)
                 {
                     effect.BeginPass(i);
     
                     device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 10);
     
                     Matrix LamppostWorld = Matrix.Scaling(0.05f, 0.05f, 0.05f) * Matrix.RotationX((float)Math.PI / 2) * Matrix.Translation(-4.0f, 5, 1);
                     effect.SetValue("xWorldViewProjection", LamppostWorld * matView * matProjection);
                     DrawMesh(Lamppost, LamppostMaterials, LamppostTextures);
     
                     LamppostWorld = Matrix.Scaling(0.05f, 0.05f, 0.05f) * Matrix.RotationX((float)Math.PI / 2) * Matrix.Translation(-4.0f, 35, 1);
                     effect.SetValue("xWorldViewProjection", LamppostWorld * matView * matProjection);
                     DrawMesh(Lamppost, LamppostMaterials, LamppostTextures);
     
                     Matrix CarWorld = Matrix.Scaling(4f, 4f, 4f) * Matrix.RotationYawPitchRoll((float)Math.PI / 2, (float)Math.PI / 2, (float)Math.PI / 2) * Matrix.Translation(3, 15, 0f);
                     effect.SetValue("xWorldViewProjection", CarWorld * matView * matProjection);
                     DrawMesh(Car, CarMaterials, CarTextures);
     
                     CarWorld = Matrix.Scaling(4f, 4f, 4f) * Matrix.RotationYawPitchRoll((float)Math.PI / 2, (float)Math.PI / 8, (float)Math.PI / 2) * Matrix.Translation(28, -1.9f, 0f);
                     effect.SetValue("xWorldViewProjection", CarWorld * matView * matProjection);
                     DrawMesh(Car, CarMaterials, CarTextures);
                     effect.EndPass();
                 }
                 effect.End();
     
                 UpdateFramerate();
     
                 device.EndScene();
                 device.Present();
                 this.Invalidate();    
             }
     
             private void UpdateFramerate()
             {
                 Frames++;
                 if (Math.Abs(Environment.TickCount - LastTickCount) > 1000)
                 {
                     LastFrameRate = (float)Frames * 1000 / Math.Abs(Environment.TickCount - LastTickCount);
                     LastTickCount = Environment.TickCount;
                     Frames = 0;
                 }
                 text.DrawText(null, string.Format("Framerate : {0:0.00} fps", LastFrameRate), new Point(10, 430), Color.Red);
             }
     
             private void SetUpCamera()
             {
                 CameraPos = new Vector3(25, -18, 13);
                 matProjection = Matrix.PerspectiveFovLH((float)Math.PI / 4, this.Width / this.Height, 0.3f, 200f);
                 matView = Matrix.LookAtLH(CameraPos, new Vector3(0, 12, 2), new Vector3(0, 0, 1));
             }
     
             private void LoadMesh(string filename, ref Mesh mesh, ref Material[] meshmaterials, ref Texture[] meshtextures)
             {
                 ExtendedMaterial[] materialarray;
                 GraphicsStream adj = null;
     
                 mesh = Mesh.FromFile(filename, MeshFlags.Managed, device, out adj, out materialarray);
     
                 if ((materialarray != null) && (materialarray.Length > 0))
                 {
                     meshmaterials = new Material[materialarray.Length];
                     meshtextures = new Texture[materialarray.Length];
     
                     for (int i = 0; i < materialarray.Length; i++)
                     {
                         meshmaterials[i] = materialarray[i].Material3D;
                         meshmaterials[i].Ambient = meshmaterials[i].Diffuse;
     
                         if ((materialarray[i].TextureFilename != null) && (materialarray[i].TextureFilename != string.Empty))
                         {
                             meshtextures[i] = TextureLoader.FromFile(device, materialarray[i].TextureFilename);
                         }
                     }                
                 }
     
                 mesh = mesh.Clone(mesh.Options.Value, CustomVertex.PositionNormalTextured.Format, device);
                 mesh.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 = "Riemer's DirectX & HLSL Tutorial using C# -- Season 3";
             }
     
             static void Main()
             {
                 using (WinForm our_directx_form = new WinForm())
                 {
                     our_directx_form.InitializeDevice();                
                     our_directx_form.AllocateResources();
                     our_directx_form.FillResources();
                     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 - 2011 Riemer Grootjans
  • Translations

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

    Microsoft MVP Award



    2007 - 2011 MVP Award
    DirectX - XNA

    Contents

    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)
    Series 2: Flightsim (19)
    Series 3: HLSL (19)
    Starting point
    HLSL Introduction
    Vertex Shader
    Shaded triangle
    Pixel Shader
    Textured Triangle
    Triangle Strip
    World transform
    Adding normals
    The first light
    Shadow mapping
    Render To Texture
    Projective texturing
    The first shadow
    Shaping the light
    Preshaders
    Multiple lights
    Adjusting Z values
    Finishing touch
    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!