ASP.NET
  Home arrow ASP.NET arrow Page 13 - Managed DirectX First Steps: Direct 3D Bas...
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Silverlight  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
ASP Web Hosting  
ASP.NET Web Hosting 
Windows Web Hosting
 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
ASP.NET

Managed DirectX First Steps: Direct 3D Basics and DirectX vs. GDI+
By: Apress Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 65
    2005-01-26

    Table of Contents:
  • Managed DirectX First Steps: Direct 3D Basics and DirectX vs. GDI+
  • DirectX Overview
  • Referencing DirectX Libraries
  • Put That in Your Pipeline and Shade It
  • 3-D Coordinate Systems and Projections
  • Drawing Primitives and Texture
  • The Application Proposal
  • The Coding Phase
  • Second Step: Coding Your First Windowed Test
  • Code the Render Procedure
  • Fourth Step: Using Transparent Textures
  • Fifth Step: Changing Diffuse Colors
  • Sixth Step: Testing Matrix Transformations
  • Adding the Final Touches

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Managed DirectX First Steps: Direct 3D Basics and DirectX vs. GDI+ - Sixth Step: Testing Matrix Transformations


    (Page 13 of 14 )

    Adapting the sample to test the matrix transformations, according to what we discussed earlier in this chapter, will be your last and hardest challenge; but if you missed some previous point, this is the perfect way to reinforce the concepts.

    Because you’re facing a lot of modifications in many procedures, let’s see all the code for this sample, starting with the vertex definition. Rather than using the flexible vertex format structure that you’ve already seen, you’ll instead use one of the several predefined vertex formats defined in Managed DirectX. In this case, you want to use a simple vertex format that supports position and texture, but you’ll abandon the rhw parameter that indicated in the previous samples that you were working on screen (already transformed) coordinates. In this sample, you’ll test all the transformations from world coordinates to screen coordinates. Such a format is defined in the CustomVertex class as the static type PositionedTextured, which contains values for the x, y, and z coordinates, as well as the tu and tv texture coordinates.

    Now, instead of calling the CreateFlexVertex method, you simply invoke the custom vertex constructor, like this:

    CustomVertex.PositionedTextured cv =
           new CustomVertex.PositionTextured(0, 0, 0, 0, 0);

    Returning to the first example, note that you have an initialization function and a finalization function, which creates the objects you need and destroys them when the window is being closed. Although the DisposeD3D finalization procedure needs no modifications (it just disposes every object), the InitD3D procedure for this sample deserves a closer look, because you have some significant modifications, which appear in bold in the subsequent code:

    public bool InitD3D(IntPtr winHandle) {
       DisplayMode DispMode =
          Manager.Adapters[Manager.Adapters.Default.Adapter].
            CurrentDisplayMode;
       PresentParameters presentParams = new PresentParameters
            ();
       // Define the presentation parameters. 
       presentParams.Windowed = true;
       presentParams.SwapEffect = SwapEffect.Discard; 
       presentParams.BackBufferFormat = DispMode.Format;
      
    presentParams.EnableAutoDepthStencil = true
       presentParams.AutoDepthStencilFormat = DepthFormat.D16;
       // Try to create the device
    .
       try {
           device = new Device
            (Manager.Adapters.Default.Adapter,
              DeviceType.Hardware, winHandle,  
              CreateFlags.SoftwareVertexProcessing,
                presentParams);
           // Turn off culling => front and back of the
                triangles are visible
    .
           device.RenderState.CullMode = Cull.None;
           // Turn off D3D lighting.   
           device.RenderState.Lighting = false;
           // Turn on ZBuffer.
           device.RenderState.ZBufferEnable = true;
           device.VertexFormat = customVertex;
           // Set the Projection Matrix to use an orthogonal 
                view.
           device.Transform.Projection = Matrix.OrthoLH(300,
                200, -200, +200);
          
    return true;
       }
       catch {
          
    return false;
       }
    }

    Because you’re working in a 3-D world now, you need to instruct Direct3D to calculate which drawing primitives are shown and which aren’t. This is made by setting the EnableAutoDepthStencil member of the presentation parameter to true (yes, you want a depth stencil to be used) and setting the AutoDepthStencilFormat to DepthFormat.D16 (16 bits will be used in the calculation, because this is the value most commonly supported by the current 3-D boards). You’ll also need to turn on the z-buffer (another name for depth buffer or depth stencil) calculation for the device.

    There are two other important settings here: the one that disables the drawing primitives’ culling (so the textures will be drawn in the front face) and the one that turns off the lighting for your 3-D world (in other words, the one that tells the device to light everything equally). A nice test is to comment out each of these lines and see the resulting effects.

    The last bold line defines an orthogonal projection matrix to be used when converting the world coordinates to screen ones, with a viewport of 300 pixels wide and 200 pixels tall. This is the simplest projection type, but the z-axis translation will have no effect (you won’t see the cube getting smaller when it’s far from the screen).

    After initializing the objects, you need to load the vertices and textures. You can create a CreateCube function that will initialize and lock the vertex buffer, and then set up an event handler to respond anytime the vertex buffer needs to be re-created (for instance, whenever the device gets reset). That handler, called OnVertexBufferCreate, will also be initially called to give all the vertices their initial values.

    public bool CreateCube() {
       try {
          string txName;
          for(int i=1; i<=10; i++) {
             txName = Application.StartupPath+"\\
                    Walk"+i.ToString()+".bmp";
             textures[i-1] =
                TextureLoader.FromFile(device, txName);
       }
       vertBuffer =
          new VertexBuffer(typeof(CustomVertex.Position
                Textured), numVerts,
                        
    device, Usage.WriteOnly,
                        
    CustomVertex.PositionTextured.Format,
                           Pool.Default);
       vertBuffer.Created += new EventHandler
                (this.OnVertexBufferCreate);
       OnVertexBufferCreate(vertBuffer, null);
       return true;
       }
       catch {
          return false;
       }
    }

    The OnVertexBufferCreate function will create each of the vertices of the cube, providing their 3-D coordinates. It’s always a good idea to have a paper and a pencil at hand when creating simple 3-D models, so you can draft the figure and understand better how the vertices fit together. Just take a look at Figure 3-30 and compare it to the first lines of the OnVertexBufferCreate function; because the lines that created the other vertices are very similar, we are showing here just the vertices for the first two facets.


    Figure 3-30.  The cube 3-D coordinates for the first two facets

    private void OnVertexBufferCreate(object sender, EventArgs
          e) {
       VertexBuffer buffer = (VertexBuffer)sender;  
       CustomVertex.PositionTextured[] verts =
            
    new CustomVertex.PositionTextured[numVerts];
       // 1st facet -------------------------------------------

       // Triangle 1.
       verts[0] = new CustomVertex.PositionTextured(0, 0, 0, 
                0, 0);
       verts[1] = new CustomVertex.PositionTextured(90, 0, 0,
                1, 0);
       verts[2] = new CustomVertex.PositionTextured(0, 90, 0,
                0, 1);
       // Triangle 2.
       verts[3] = new CustomVertex.PositionTextured(0, 90, 0,
                0, 1);
       verts[4] = new CustomVertex.PositionTextured(90, 0, 0,
                1, 0);
       verts[5] = new CustomVertex.PositionTextured(90, 90, 0,
                1, 1);
      
    // 2nd facet -------------------------------------------   // Triangle 1.
       verts[6] = new CustomVertex.PositionTextured(90, 0, 0,
                0, 0);
       verts[7] = new CustomVertex.PositionTextured(90, 90, 0,
                1, 0);
       verts[8] = new CustomVertex.PositionTextured(90, 0, 90,
                0, 1);
      
    // Triangle 2.
       verts[9] = new CustomVertex.PositionTextured(90, 0, 90,
                0, 1);
       verts[10] = new CustomVertex.PositionTextured(90, 90,
                0, 1, 0);
       verts[11] = new CustomVertex.PositionTextured(90, 90,
                90, 1, 1);     …
    }


    TIP  Observe that many duplicated vertices appear in the previous sample code. Opt to use a triangle list, as it would be difficult (and a lot less clear for these purposes) to use a composition of triangle strips; but in a real game it’s always good practice to try to reduce the number of vertices.

    Your render procedure will have no difference from the previous samples, except for the inclusion of an automatic generation of a rotation matrix (in bold), as defined in the game project, which will move the cube around according to the processor clock tick.

    public void Render() {
       int Tick;
       if ((device==null)) return;
       // Move the cube automatically.
       if (chkAuto.Checked) {
          Tick = Environment.TickCount;
          device.Transform.World = Matrix.RotationAxis(
             new Vector3((float)Math.Cos((double)Tick/3000.0F),
                   1,
            (float)Math.Sin((double)Tick/3000.0F)),
                   Tick/3000.0F);
       }
       device.Clear(ClearFlags.Target|ClearFlags.ZBuffer, 
                            Color.FromArgb(255, 0, 0, 255),
                              1.0F, 0);
       device.BeginScene();
      
    // Show one texture at a time in order to create the
             illusion of a walking guy.
       device.SetTexture(0, textures[x]);
       x = (x == 9) ? 0 : x+1; //If x is 9, set to 0,
             otherwise increment x
       device.SetStreamSource(0, vertBuffer, 0);
       device.DrawPrimitives(PrimitiveType.TriangleList, 0,
              numVerts/3);
       device.EndScene();
       try {
           device.Present();
       }
       catch {
          
    // This can lead to an error if the window is closed
           // while the scene is being rendered.
       }
    }

    Note that the rest of the rendering code is exactly the same as that of the previous samples.

    The last part of your test is to update the Transform.World matrix device member to the values set in the numeric up-down controls, as defined in the visual prototype in the project phase.

    Using the trick you learned in the light sample, you can create a single procedure that will handle the events for all the controls. In order to make your code more understandable, create three helper functions that will add the rotation, translation, and scale transformations to the world matrix.

    private void Transformations_ValueChanged(object sender,
             System.EventArgs e) {
       if(device != null) {
          device.Transform.World = Matrix.Identity;  
          RotationMatrices((float)RotationX.Value, (float)
             RotationY.Value,
          (float)RotationZ.Value);
          TranslationMatrices((float)TranslationX.Value,
                 (float)TranslationY.Value,
             (float)TranslationZ.Value);
          ScaleMatrices((float)ScaleX.Value,(float)
             ScaleY.Value,
                                 (float)ScaleZ.Value);
       }
    }
    // The following functions create the transformation matrices for each operation.
    public void RotationMatrices(float x, float y, float z) {  
       device.Transform.World = Matrix.Multiply
          (device.Transform.World,
         Matrix.RotationX((float)(x * Math.PI / 180))); 
       device.Transform.World = Matrix.Multiply
         (device.Transform.World,
          Matrix.RotationY((float)(y * Math.PI / 180)));
       device.Transform.World = Matrix.Multiply
         (device.Transform.World,
          Matrix.RotationZ((float)(z * Math.PI / 180)));
    }
    public void TranslationMatrices(float x, float y, float
             z) {
         device.Transform.World = Matrix.Multiply
            (device.Transform.World,
            Matrix.Translation(x, y, z));
    }
    public void ScaleMatrices(float x, float y, float z) {
         device.Transform.World = Matrix.Multiply
            (device.Transform.World,
            Matrix.Scaling(x / 100, y / 100, z / 100));
    }

    The most important part of this code is to remember that you can add transformations by multiplying the matrices (using the Multiply method of the Matrix object). In the Transformations_ValueChanged event procedure, you use the Matrix.Identity function to reset any transformations in the Transform.World matrix, so you can be sure that any matrix multiplication that occurred in the last call to this function is ignored and doesn’t affect the current matrices.

    To finish the code and start the test, all you must take care of is to provide good starting values for your matrix transformations; setting the Scale up-down controls with the default value of zero, for example, will simply make your object disappear from screen.

    The code for the click event on the button of the main form is as follows:

    using (MatrixControl matrixControl = new MatrixControl()) {
       MatrixTest matrixTest = new MatrixTest();  
       matrixControl.Show();
       matrixTest.Show();
       // Initialize Direct3D and the Device object.
      
    if(!matrixControl.InitD3D(matrixTest.Handle)) {
          MessageBox.Show("Could not initialize
              Direct3D.");
          matrixControl.Dispose();
          return;
      
    }
      
    else {
          // Load the textures and create the cube to show
               them.
          if(!matrixControl.CreateCube()) {
            
    MessageBox.Show("Could not initialize
               geometry."); 
             matrixControl.DisposeD3D();
             matrixControl.Dispose();
             return;
          }
       }
      
    // Start with a simple rotation, to position the cube
               more nicely,
       // and with no scale (100% of the original size).
      
    matrixControl.RotationX.Value = 45;
       matrixControl.RotationY.Value = 45;
      
    matrixControl.RotationZ.Value = 45;
      
    matrixControl.ScaleX.Value = 100;
      
    matrixControl.ScaleY.Value = 100;
      
    matrixControl.ScaleZ.Value = 100;
      
    // Ends the test if ESC is pressed in any of the 2
               windows.
      
    while(!matrixControl.EndTest && !matrixTest.EndTest) {
         
    matrixControl.Render();
         
    // Frame rate calculation.
         
    matrixTest.Text = "Matrix Tests. Frame Rate: " +
                  DirectXLists.CalcFrameRate().ToString();  
          Application.DoEvents();
       }
    }

    Now you can finally run the test. Modifying the values of the numeric up-down controls in the control window will let you see the transformation occurring dynamically; choosing the Auto Move check box will make the cube perform some nice moves automatically on screen. Figure 3-31 shows an example result of this last test.


    Figure 3-31.  A moving cube with a walking man in each face

    This chapter is from Beginning .NET Game Programming in C# by David Weller et. al.(Apress, 2004, ISBN: 1590593197). Check it out at your favorite bookstore today. Buy this book now.

    More ASP.NET Articles
    More By Apress Publishing


     

    ASP.NET ARTICLES

    - Adding Content to a Static ASP.NET Website
    - Building a Static ASP.NET Website in a Basic...
    - Develop Your First ASP.NET Website with Visu...
    - Run ASP.NET in Windows XP Home with Cassini ...
    - How to Test a Web Application
    - How to Add Code and Validation Controls to a...
    - Working in Source and Split Views to Build a...
    - How to Build a Web Form for a One-Page Web A...
    - How to Develop a One-Page Web Application
    - An ASP.NET Web Application in Action
    - Developing ASP.NET Web Applications
    - An Introduction to ASP.NET Web Programming
    - Introduction to the ADO.NET Entity Framework...
    - Completing an In-Text Advertising System und...
    - Programming an In-Text Advertising System un...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 1 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek