XNA for C#
DirectX 9 for C#
DirectX 9 for C++
DirectX 9 for VB
Forum
   July 19: Series4 - 2 Pass Renderstates
My Book: Out Now!
      
       Go to section on this site

Additional info


Latest Forum posts

 WinForm not found
  Posted by: riemer
  When: 20/07/2008 at 14:30:03

 Bounding Boxes for Maya Data
  Posted by: riemer
  When: 20/07/2008 at 14:27:31

 QuadTree
  Posted by: riemer
  When: 20/07/2008 at 14:23:48

 Bounding Boxes for Maya Data
  Posted by: vijay
  When: 20/07/2008 at 12:25:40

 Error on compiling
  Posted by: libia
  When: 20/07/2008 at 02:36:16

 Terrain From RAW
  Posted by: reiko
  When: 19/07/2008 at 20:36:39

 WinForm not found
  Posted by: kapil.rajak
  When: 19/07/2008 at 16:24:52

 human skin colors
  Posted by: aguacate
  When: 19/07/2008 at 13:34:55

 Bounding Boxes for Maya Data
  Posted by: Archenon
  When: 19/07/2008 at 09:19:16

 Volunteer to write VB.net tutorial
  Posted by: riemer
  When: 19/07/2008 at 07:00:19


Ads

Adding more lights to our scene

Up till now we have one correctly working light in our scene. Let’s see how we can get our 2 lampposts working.

First we have to find out how we can store the depthinfo of 3 different light sources in one texture, the shadow map. Up till now, we stored this depth as a gray value. This chapter, we’ll be storing the depth of each light as a different color channel of this texture: the distance to the first light will be stored in the red color channel, the distance of the second light in the green channel and the third in the blue channel.

Let’s start by updating our DirectX code. Because we’re using preshaders, the only method we need to update is the UpdateLightData method:

 private void UpdateLightData()
 {
     Vector3[] LightPos = new Vector3[3];
     LightPos[0] = new Vector3(18, 2, 5);
     LightPos[1] = new Vector3(-5, 5, 11.5f);
     LightPos[2] = new Vector3(-5, 35, 11.5f);
 
     float[] LightPower = new float[3];        
     LightPower[0] = 1.1f;
     LightPower[1] = 0.6f;
     LightPower[2] = 0.6f;
             
     Matrix[] LightViewProjection = new Matrix[3];
     LightViewProjection[0] = Matrix.LookAtLH(LightPos[0], new Vector3(2, 10, -3), new Vector3(0, 0, 1)) * Matrix.PerspectiveFovLH((float)Math.PI / 2, this.Width / this.Height, 1f, 100f);
     LightViewProjection[1] = Matrix.LookAtLH(LightPos[1], new Vector3(-5, 5, 0), new Vector3(0, 1, 0)) * Matrix.PerspectiveFovLH((float)Math.PI / 1.9f, this.Width / this.Height, 0.3f, 100f);
     LightViewProjection[2] = Matrix.LookAtLH(LightPos[2], new Vector3(-5, 35, 0), new Vector3(0, 1, 0)) * Matrix.PerspectiveFovLH((float)Math.PI / 1.9f, this.Width / this.Height, 0.3f, 100f);
             
     effect.SetValue("xLightViewProjection", LightViewProjection);
     effect.SetValue("xLightPos", V3ToV4(LightPos));
     effect.SetValue("xLightPower", LightPower);
 }

We’re doing exactly the same as before, only this time using matrices: we define the position of the 3 lights, their strength and their point of view; which form their viewing frustrum. In the end, we pass these matrices to our HLSL code.

Also make sure you pass the SpotLight to our HLSL:

 effect.SetValue("xSpotLightTexture", SpotLight);

That’s all we need to change in our DirectX code! Imagine what a mess our code would have been without using preshaders.

Next in line is the HLSL code. Change the single values to matrices:

float4x4 xLightViewProjection[3];
float4 xLightPos[3];
float xLightPower[3];

That’s how matrices are defined in HLSL. As the extra 2 lights are simply point lights, this chapter we’ll be needing the SpotLight texture:

Texture xSpotLightTexture;

sampler SpotLightSampler = sampler_state { texture = <xSpotLightTexture> ; magfilter = LINEAR; minfilter=LINEAR; mipfilter = LINEAR; AddressU = clamp; AddressV = clamp;};    
Let’s move over to the end of our file and change our techniques. We’re going to render each light during one pass, so we’ll end up with 3 passes:

technique ShadowMap
{
     pass Pass0
     {            
     cullmode = ccw;
     colorwriteenable = red;    
     VertexShader = compile vs_2_0 ShadowMapVertexShader(0);
     PixelShader = compile ps_2_0 ShadowMapPixelShader(0);
     }
     pass Pass1
     {    
     colorwriteenable = green;
     VertexShader = compile vs_2_0 ShadowMapVertexShader(1);
     PixelShader = compile ps_2_0 ShadowMapPixelShader(1);
     }    
     pass Pass2
     {    
     colorwriteenable = blue;
     VertexShader = compile vs_2_0 ShadowMapVertexShader(2);
     PixelShader = compile ps_2_0 ShadowMapPixelShader(2);
     }
}

You notice for each pass we set a renderstate so each light can only write to its own color channel of the shadow map. Perhaps even more important, we change the cullmode. The default cullmode used by HLSL is CullMode.None, which would indicate that all triangles would be drawn. Because we’ll be positioning the center of our second and third light inside our lampposts, this would mean that all these lights would see is the interior of the lampposts! Luckily, if we set the cullmode to the correct setting, the lamppost is culled away from our light point of of view (because they’re on the inside!). This renderstate will remain the same for the 2 other passes.

Also important, you’ll notice we pass a number to the vertex and pixel shader. This is called a uniform argument. In our case, this number of course indicates which light the shader will draw the shadow map for.

So let’s see how we can update our ShadowMapVertexShader so it can accept this uniform argument:

SMapVertexToPixel ShadowMapVertexShader( float4 inPos : POSITION, uniform int CurrentLight)

Next, we have to put an index at every occurrence of our 3 matrix variables. In the first vertex shader, you’ll see we’re using xLightViewProjection. Replace that line by this one:

float4x4 preLightWorldViewProjection = mul (preWorld, xLightViewProjection[CurrentLight]);

That’s it for our first vertex shader! Let’s have a look at our pixel shader, which we also have to adapt so it supports the uniform argument:

SMapPixelToFrame ShadowMapPixelShader(SMapVertexToPixel PSIn, uniform int CurrentLight)

In this shader, we’re not using any of the 3 matrix variables, but we have to update the correct color (of our shadow map) that is being written to, which corresponds to the current light:

Output.Color[CurrentLight] = PSIn.Position2D.z/xMaxDepth;

This way, the first light will update the red color channel, and so on.

So far for the first technique, let’s update our ShadowedScene technique as well:

technique ShadowedScene
{
    pass Pass0
    {    
        VertexShader = compile vs_2_0 ShadowedSceneVertexShader(0);
        PixelShader = compile ps_2_0 ShadowedScenePixelShader(0);
    }    
    pass Pass1
    {
        SRCBLEND = ONE;
        DESTBLEND = ONE;
        ALPHABLENDENABLE = true;
    
        VertexShader = compile vs_2_0 ShadowedSceneVertexShader(1);
        PixelShader = compile ps_2_0 ShadowedScenePixelShader(1);
    }
    pass Pass2
    {        
        VertexShader = compile vs_2_0 ShadowedSceneVertexShader(2);
        PixelShader = compile ps_2_0 ShadowedScenePixelShader(2);
    }
}

This technique will draw the scene 3 times using additive blending, so the intensity of a pixel will be increased for each pass the pixel is lit by the corresponding light. You can enable additive blending in the first or second pass, the result will be the same. Notice that this render state remains the same for the third pass.

You already know how to adjust the vertex shader:

SSceneVertexToPixel ShadowedSceneVertexShader( float4 inPos : POSITION, float2 inTexCoords : TEXCOORD0, float3 inNormal : NORMAL, uniform int CurrentLight)

We again need to put an index after the xLightViewProjection variable:

float4x4 preLightWorldViewProjection = mul (preWorld, xLightViewProjection[CurrentLight]);

That’s it for the vertex shader again. The last pixel shader will need some more adjustments. First of all, we have the method definition:

SScenePixelToFrame ShadowedScenePixelShader(SSceneVertexToPixel PSIn, uniform int CurrentLight)

The formulae to go to projective texture coordinates don’t change, as well as the check to see if the pixel is in the current viewing frustrum. What we do need to change, is the color of the shadow map we need to sample our stored depth from. Each light needs to sample its corresponding color:

float StoredDepthInShadowMap = tex2D(ShadowMapSampler, ProjectedTexCoords)[CurrentLight];

The code inside the last if structure also needs changing. We will adapt our code so the first light will get the shape of a carlight, while the other lights are simply shaped as a point light. The last lines also get indices where they are needed, behind the xLightPos and the xLightPower variables:

float LightTextureFactor;
if (CurrentLight == 0)
{
    LightTextureFactor = tex2D(CarLightSampler, ProjectedTexCoords).r;
}else{
    LightTextureFactor = tex2D(SpotLightSampler, ProjectedTexCoords).r;
}
    
float DiffuseLightingFactor = DotProduct(xLightPos[CurrentLight], PSIn.Position3D, PSIn.Normal);
float4 ColorComponent = tex2D(ColoredTextureSampler, PSIn.TexCoords);
Output.Color = ColorComponent*LightTextureFactor*DiffuseLightingFactor*xLightPower[CurrentLight];

That’s it! Hitting Ctrl+S shouldn’t give any problems. When you run the code, you’ll notice the shadow map has indeed become more colorful, where every color holds the distance information for a different light. However, you’ll see not everything in our scene is being lit properly. You can try to figure out what’s going on, but it’s rather difficult.




DirectX Tutorial 17 - Multiple lights

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:
  • More than 3?
          How would I go about adding more than 3 shadowed l...
  • V3ToV4 does not exist
          The name 'V3ToV4' does not exist in the current ...


    The problem is in your shadow map. Maybe you can make it a bit larger, to have a better look. See if you can find all necessary data, and if not, try to find out why not.

    Here’s our HLSL code:

    struct SMapVertexToPixel
    {
        float4 Position     : POSITION;    
        float3 Position2D    : TEXCOORD0;
    };

    struct SMapPixelToFrame
    {
        float4 Color : COLOR0;
    };

    struct SSceneVertexToPixel
    {
        float4 Position             : POSITION;
        float4 ShadowMapSamplingPos : TEXCOORD0;    
        float4 RealDistance            : TEXCOORD1;
        float2 TexCoords            : TEXCOORD2;
        float3 Normal                : TEXCOORD3;
        float3 Position3D            : TEXCOORD4;
    };

    struct SScenePixelToFrame
    {
        float4 Color : COLOR0;
    };

    //------- Constants --------
    float4x4 xCameraViewProjection;

     float4x4 xLightViewProjection[3];

    float4x4 xRotate;
    float4x4 xTranslateAndScale;


     float4 xLightPos[3];
     float xLightPower[3];

    float xMaxDepth;

    //------- Texture Samplers --------

    Texture xColoredTexture;

    sampler ColoredTextureSampler = sampler_state { texture = <xColoredTexture> ; magfilter = LINEAR; minfilter = LINEAR; mipfilter=LINEAR; AddressU = mirror; AddressV = mirror;};
    Texture xShadowMap;

    sampler ShadowMapSampler = sampler_state { texture = <xShadowMap> ; magfilter = LINEAR; minfilter = LINEAR; mipfilter=LINEAR; AddressU = clamp; AddressV = clamp;};
    Texture xCarLightTexture;

    sampler CarLightSampler = sampler_state { texture = <xCarLightTexture> ; magfilter = LINEAR; minfilter=LINEAR; mipfilter = LINEAR; AddressU = clamp; AddressV = clamp;};    

     Texture xSpotLightTexture;

    sampler SpotLightSampler = sampler_state { texture = <xSpotLightTexture> ; magfilter = LINEAR; minfilter=LINEAR; mipfilter = LINEAR; AddressU = clamp; AddressV = clamp;};    

    //------- Vertex Shaders --------


     SMapVertexToPixel ShadowMapVertexShader( float4 inPos : POSITION, uniform int CurrentLight)

    {
        SMapVertexToPixel Output = (SMapVertexToPixel)0;
        float4x4 preWorld = mul(xRotate, xTranslateAndScale);

         float4x4 preLightWorldViewProjection = mul (preWorld, xLightViewProjection[CurrentLight]);

        
        Output.Position = mul(inPos, preLightWorldViewProjection);
        Output.Position2D = Output.Position;
        
        return Output;    
    }


     SSceneVertexToPixel ShadowedSceneVertexShader( float4 inPos : POSITION, float2 inTexCoords : TEXCOORD0, float3 inNormal : NORMAL, uniform int CurrentLight)

    {
        SSceneVertexToPixel Output = (SSceneVertexToPixel)0;
        float4x4 preWorld = mul(xRotate, xTranslateAndScale);
        float4x4 preCameraWorldViewProjection = mul (preWorld, xCameraViewProjection);

         float4x4 preLightWorldViewProjection = mul (preWorld, xLightViewProjection[CurrentLight]);

        
        Output.Position = mul(inPos, preCameraWorldViewProjection);
        Output.ShadowMapSamplingPos = mul(inPos, preLightWorldViewProjection);
        Output.RealDistance = Output.ShadowMapSamplingPos.z/xMaxDepth;
        Output.TexCoords = inTexCoords;
        Output.Normal = mul(inNormal, xRotate);
        Output.Position3D = inPos;
        
        return Output;    
    }

    //------- Pixel Shaders --------

    float DotProduct(float4 LightPos, float3 Pos3D, float3 Normal)
    {
        float3 LightDir = normalize(LightPos - Pos3D);
        return dot(LightDir, Normal);
    }


     SMapPixelToFrame ShadowMapPixelShader(SMapVertexToPixel PSIn, uniform int CurrentLight)

    {
        SMapPixelToFrame Output = (SMapPixelToFrame)0;


         Output.Color[CurrentLight] = PSIn.Position2D.z/xMaxDepth;


        return Output;
    }


     SScenePixelToFrame ShadowedScenePixelShader(SSceneVertexToPixel PSIn, uniform int CurrentLight)

    {
        SScenePixelToFrame Output = (SScenePixelToFrame)0;

        float2 ProjectedTexCoords;
        ProjectedTexCoords[0] = PSIn.ShadowMapSamplingPos.x/PSIn.ShadowMapSamplingPos.w/2.0f +0.5f;
        ProjectedTexCoords[1] = -PSIn.ShadowMapSamplingPos.y/PSIn.ShadowMapSamplingPos.w/2.0f +0.5f;

        if ((saturate(ProjectedTexCoords.x) == ProjectedTexCoords.x) && (saturate(ProjectedTexCoords.y) == ProjectedTexCoords.y))
        {

             float StoredDepthInShadowMap = tex2D(ShadowMapSampler, ProjectedTexCoords)[CurrentLight];    

            if ((PSIn.RealDistance.x - 1.0f/100.0f) <= StoredDepthInShadowMap)    
            {

                 float LightTextureFactor;
                 if (CurrentLight == 0)
                 {
                     LightTextureFactor = tex2D(CarLightSampler, ProjectedTexCoords).r;
                 }else{
                     LightTextureFactor = tex2D(SpotLightSampler, ProjectedTexCoords).r;
                 }
         
                 float DiffuseLightingFactor = DotProduct(xLightPos[CurrentLight], PSIn.Position3D, PSIn.Normal);

                float4 ColorComponent = tex2D(ColoredTextureSampler, PSIn.TexCoords);

                 Output.Color = ColorComponent*LightTextureFactor*DiffuseLightingFactor*xLightPower[CurrentLight];

            }
        }    

        return Output;
    }

    //------- Techniques --------

    technique ShadowMap
    {

         pass Pass0
         {            
             cullmode = ccw;
             colorwriteenable = red;    
             VertexShader = compile vs_2_0 ShadowMapVertexShader(0);
             PixelShader = compile ps_2_0 ShadowMapPixelShader(0);
         }
         pass Pass1
         {    
             colorwriteenable = green;
             VertexShader = compile vs_2_0 ShadowMapVertexShader(1);
             PixelShader = compile ps_2_0 ShadowMapPixelShader(1);
         }    
         pass Pass2
         {    
             colorwriteenable = blue;
             VertexShader = compile vs_2_0 ShadowMapVertexShader(2);
             PixelShader = compile ps_2_0 ShadowMapPixelShader(2);
         }

    }

    technique ShadowedScene
    {

         pass Pass0
         {    
             VertexShader = compile vs_2_0 ShadowedSceneVertexShader(0);
             PixelShader = compile ps_2_0 ShadowedScenePixelShader(0);
         }    
         pass Pass1
         {
              SRCBLEND = ONE;
             DESTBLEND = ONE;
             ALPHABLENDENABLE = true;
         
             VertexShader = compile vs_2_0 ShadowedSceneVertexShader(1);
             PixelShader = compile ps_2_0 ShadowedScenePixelShader(1);
         }
         pass Pass2
         {        
             VertexShader = compile vs_2_0 ShadowedSceneVertexShader(2);
             PixelShader = compile ps_2_0 ShadowedScenePixelShader(2);
         }

    }

    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 Vector3 Normal;
             public Vector2 TexCoord;
     
             public myownvertexformat(Vector3 _Pos, Vector3 _Normal, float texx, float texy)
             {
                 Pos = _Pos;
                 Normal = _Normal;
                 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 Texture CarLight;
             private Texture SpotLight;
             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;
     
             private RenderToSurface RtsHelper;
             private Texture RenderTexture;
             private Surface RenderSurface;
             private int RenderSurfaceSize = 512;
     
             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), 18, 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[18];
     
                 vertices[0] = new myownvertexformat(new Vector3(20, -10, 0), new Vector3(0, 0, 1), -0.25f, 25.0f);
                 vertices[1] = new myownvertexformat(new Vector3(20, 100, 0), new Vector3(0, 0, 1), -0.25f, 0.0f);
                 vertices[2] = new myownvertexformat(new Vector3(-2, -10, 0), new Vector3(0, 0, 1), 0.25f, 25.0f);                        
                 vertices[3] = new myownvertexformat(new Vector3(-2, 100, 0), new Vector3(0, 0, 1), 0.25f, 0.0f);
                 vertices[4] = new myownvertexformat(new Vector3(-2, -10, 0), new Vector3(1, 0, 0), 0.25f, 25.0f);                        
                 vertices[5] = new myownvertexformat(new Vector3(-2, 100, 0), new Vector3(1, 0, 0), 0.25f, 0.0f);
                 vertices[6] = new myownvertexformat(new Vector3(-2, -10, 1), new Vector3(1, 0, 0), 0.375f, 25.0f);
                 vertices[7] = new myownvertexformat(new Vector3(-2, 100, 1), new Vector3(1, 0, 0), 0.375f, 0.0f);
                 vertices[8] = new myownvertexformat(new Vector3(-2, -10, 1), new Vector3(0, 0, 1), 0.375f, 25.0f);
                 vertices[9] = new myownvertexformat(new Vector3(-2, 100, 1), new Vector3(0, 0, 1), 0.375f, 0.0f);
                 vertices[10] = new myownvertexformat(new Vector3(-3, -10, 1), new Vector3(0, 0, 1), 0.5f, 25.0f);
                 vertices[11] = new myownvertexformat(new Vector3(-3, 100, 1), new Vector3(0, 0, 1), 0.5f, 0.0f);
                 vertices[12] = new myownvertexformat(new Vector3(-13, -10, 1), new Vector3(0, 0, 1), 0.75f, 25.0f);
                 vertices[13] = new myownvertexformat(new Vector3(-13, 100, 1), new Vector3(0, 0, 1), 0.75f, 0.0f);
                 vertices[14] = new myownvertexformat(new Vector3(-13, -10, 1), new Vector3(1, 0, 0), 0.75f, 25.0f);
                 vertices[15] = new myownvertexformat(new Vector3(-13, 100, 1), new Vector3(1, 0, 0), 0.75f, 0.0f);
                 vertices[16] = new myownvertexformat(new Vector3(-13, -10, 21), new Vector3(1, 0, 0), 1.25f, 25.0f);
                 vertices[17] = new myownvertexformat(new Vector3(-13, 100, 21), new Vector3(1, 0, 0), 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.Float3, DeclarationMethod.Default, DeclarationUsage.Normal, 0),
                     new VertexElement(0, 24, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0),
                     VertexElement.VertexDeclarationEnd
                 };
                 vd = new VertexDeclaration(device, velements);
     
                 StreetTexture = TextureLoader.FromFile(device, "streettexture.jpg");
                 CarLight = TextureLoader.FromFile(device, "carlight.jpg");
                 SpotLight = TextureLoader.FromFile(device, "spotlight.jpg");
                 effect.SetValue("xColoredTexture", StreetTexture);
                 effect.SetValue("xCarLightTexture", CarLight);
                 effect.SetValue("xSpotLightTexture", SpotLight);
                 LoadMesh("lamppost.x", ref Lamppost, ref LamppostMaterials, ref LamppostTextures);
                 LoadMesh("car.x", ref Car, ref CarMaterials, ref CarTextures);            
     
                 RtsHelper = new RenderToSurface(device, RenderSurfaceSize, RenderSurfaceSize, Format.X8R8G8B8, true, DepthFormat.D16);
                 RenderTexture = new Texture(device, RenderSurfaceSize, RenderSurfaceSize, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default);
                 RenderSurface = RenderTexture.GetSurfaceLevel(0);
             }
     
             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)
             {
                 UpdateLightData();
                 GenerateShadowMap();
     
                 device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
                 device.BeginScene();
     
                 RenderShadowedScene();
                 using (Sprite spriteobject = new Sprite(device))
                 {
                     spriteobject.Begin(SpriteFlags.DoNotSaveState);
                     spriteobject.Transform = Matrix.Scaling(0.25f, 0.25f, 0.25f);
                     spriteobject.Draw(RenderTexture, new Rectangle(0, 0, RenderSurfaceSize, RenderSurfaceSize), new Vector3(0, 0, 0), new Vector3(0, 0, 0), Color.White);
                     spriteobject.End();
                 }
                 UpdateFramerate();
     
                 device.EndScene();
                 device.Present();
                 this.Invalidate();    
             }
     
             private void GenerateShadowMap()
             {
                 RtsHelper.BeginScene(RenderSurface);            
                 device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);            
     
                 effect.Technique = "ShadowMap";
                 effect.SetValue("xMaxDepth", 60);            
                 int numpasses = effect.Begin(0);
                 for (int i = 0; i < numpasses; i++)
                 {
                     effect.BeginPass(i);
                     DrawScene();
                     effect.EndPass();
                 }        
                 effect.End();
     
                 RtsHelper.EndScene(Filter.None);
             }
     
             private void RenderShadowedScene()
             {
                 effect.Technique = "ShadowedScene";
                 effect.SetValue("xShadowMap", RenderTexture);
                 
                 int numpasses = effect.Begin(0);
                 for (int i = 0; i < numpasses; i++)
                 {
                     effect.BeginPass(i);
                     DrawScene();
                     effect.EndPass();
                 }        
                 effect.End();
             }
     
             private void UpdateLightData()
             {
     Vector3[] LightPos = new Vector3[3];
                 LightPos[0] = new Vector3(18, 2, 5);
                 LightPos[1] = new Vector3(-5, 5, 11.5f);
                 LightPos[2] = new Vector3(-5, 35, 11.5f);
     
                 float[] LightPower = new float[3];        
                 LightPower[0] = 1.1f;
                 LightPower[1] = 0.6f;
                 LightPower[2] = 0.6f;
                 
                 Matrix[] LightViewProjection = new Matrix[3];
                 LightViewProjection[0] = Matrix.LookAtLH(LightPos[0], new Vector3(2, 10, -3), new Vector3(0, 0, 1)) * Matrix.PerspectiveFovLH((float)Math.PI / 2, this.Width / this.Height, 1f, 100f);
                 LightViewProjection[1] = Matrix.LookAtLH(LightPos[1], new Vector3(-5, 5, 0), new Vector3(0, 1, 0)) * Matrix.PerspectiveFovLH((float)Math.PI / 1.9f, this.Width / this.Height, 0.3f, 100f);
                LightViewProjection[2] = Matrix.LookAtLH(LightPos[2], new Vector3(-5, 35, 0), new Vector3(0, 1, 0)) * Matrix.PerspectiveFovLH((float)Math.PI / 1.9f, this.Width / this.Height, 0.3f, 100f);
                 
                 effect.SetValue("xLightViewProjection", LightViewProjection);
                 effect.SetValue("xLightPos", V3ToV4(LightPos));
                 effect.SetValue("xLightPower", LightPower);
             }
     
             private Vector4[] V3ToV4(Vector3[] In)
             {
                 Vector4[] Out = new Vector4[3];
                 for (int i = 0; i < 3; i++)
                 {
                     Out[i] = new Vector4(In[i].X, In[i].Y, In[i].Z, 1);
                 }
                 return Out;
             }
     
             private void DrawScene()
             {            
                 effect.SetValue("xRotate", Matrix.Identity);
                 effect.SetValue("xTranslateAndScale", Matrix.Identity);            
                 effect.SetValue("xColoredTexture", StreetTexture);
                 effect.CommitChanges();
                 device.SetStreamSource(0, vb, 0);
                 device.VertexDeclaration = vd;
                 device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 16);
     
                 effect.SetValue("xRotate", Matrix.RotationX((float)Math.PI / 2));
                 effect.SetValue("xTranslateAndScale", Matrix.Scaling(0.05f, 0.05f, 0.05f) * Matrix.Translation(-4.0f, 5, 1));
                 effect.CommitChanges();
                 DrawMesh(Lamppost, LamppostMaterials, LamppostTextures);
     
                 effect.SetValue("xTranslateAndScale", Matrix.Scaling(0.05f, 0.05f, 0.05f) * Matrix.Translation(-4.0f, 35, 1));
                 effect.CommitChanges();
                 DrawMesh(Lamppost, LamppostMaterials, LamppostTextures);
     
                 effect.SetValue("xRotate", Matrix.RotationYawPitchRoll((float)Math.PI / 2, (float)Math.PI / 2, (float)Math.PI / 2));
                 effect.SetValue("xTranslateAndScale", Matrix.Scaling(4f, 4f, 4f) * Matrix.Translation(3, 15, 0f));
                 DrawMesh(Car, CarMaterials, CarTextures);
     
                 effect.SetValue("xRotate", Matrix.RotationYawPitchRoll((float)Math.PI / 2, (float)Math.PI / 8, (float)Math.PI / 2));
                 effect.SetValue("xTranslateAndScale", Matrix.Scaling(4f, 4f, 4f) * Matrix.Translation(28, -1.9f, 0f));
                 DrawMesh(Car, CarMaterials, CarTextures);
             }
     
             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));
                 effect.SetValue("xCameraViewProjection", matView * matProjection);
             }
     
             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 - 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 (136)
    XNA 2.0 using C# (65)
    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