|
|
|
|
Rendering our scene into a texture – Displaying 2D images using the Sprite object |
This chapter again has nothing to do with HLSL, so anyone only interested in the Render-To-Texture technique will be able to follow.
Except for this paragraph :) As I told you last chapter, the second step of the shadow mapping algorithm involves comparing values in our depth map. To so this, we will save the screen of last chapter (the depth map) into a texture, so we can use this texture during the second step.
So we’ll be drawing our scene not to the screen, but to a texture instead. This can be useful for example to create a mirror in your scene: first you render the scene as seen by the mirror into the texture, afterwards you draw your scene while texturing two triangles with the rendered texture.
Thanks to DirectX and some of its helper classes, this rendering your scene into a texture is made pretty easy. We’ll need these variables:
private RenderToSurface RtsHelper; private Texture RenderTexture; private Surface RenderSurface; private int RenderSurfaceSize = 512;
The first line is the helper class that will let you draw your scene to the texture, which is the second line. A texture can have multiple mipmap levels. The first level will be the most detailed, the second one will be half the width and the height of the first one and so on. When the texture is close to the camera, the full-detailed first level map will be used to draw from. When the texture is further away from the camera, however, a smaller lower-detail mipmap is used, which reduces bandwidth.
The RenderSurface variable will link to this first level mipmap, which is in fact what we will render to. The last element indicates the width and height of this mipmap. The larger this value, the more detailed you shadow map will be, because there will be more pixels in it. These pixels also will have to be drawn by you pixel shader, so using big values can slow down performance.
Now we have initialized our variables, it’s time to fill them in our FillResources method:
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);
The first line stores a new RenderToSurface object into our variable. This object needs to be linked to the device, as we will still need our graphics cards to render to the texture. Next we need to specify the number of pixels to render, by defining the width and the height of the viewport. As with our presentation parameters, we also need to set the color format as well as the depth format of our render target. The second last parameter indicates whether we want our device to perform the Z-test, and corresponds to the EnableAutoDepthStencil member of the presentation parameters.
The next line creates a new (empty) texture. We will again need to specify a link to the device, as well as the width and height of the texture. Because in this example we don’t need a complete mipmap tree, and will suffice with the first level, we indicate our texture will only need 1 mipmap level. We indicate this texture will be used to render to. Usage.RenderTarget only works when the resource is stored in the Default memory pool.
Next, we select this first mipmap level and store a link to it in our RenderSurface variable, which is where we’ll actually be rendering to.
Now we’ve got all our variables set up, it’s time to modify GenerateShadowMap, the method where we draw our scene. It’s very easy: instead of using device.BeginScene and device.EndScene, we use RtsHelper.BeginScene and RtsHelper.EndScene:
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); }
Only the first 2 lines and the last line are new; the remaining code draws our scene. Note we also have to clear our rendertarget.
When you would run the code at this point, you should get an error. This is because our call to device.BeginScene is followed immediately by a call to RtsHelper.BeginScene, before we call device.EndScene. So what you have to do in your OnPaint method is put the call to GenerateShadowMap before the call to device.BeginScene. This way, we will first process our render-to-texture method, and afterwards our render-to-screen part.
Try running this code. Now everything should be OK, but you’ll get a completely black screen. This is because we render our scene to a texture, but we’re not displaying this texture on our screen!
Instead of using 2 triangles to display the texture, we’ll take a shortcut by using the Sprite class. A sprite object can be used to display 2D images from a texture using Direct3D. Note you can also use this to load 2D images from file and display them easily! Put this between your calls to device.BeginScene and device.EndScene:
using (Sprite spriteobject = new Sprite(device)) { spriteobject.Begin(SpriteFlags.DoNotSaveState); spriteobject.Transform = Matrix.Scaling(0.4f, 0.4f, 0.4f); spriteobject.Draw(RenderTexture, new Rectangle(0, 0, RenderSurfaceSize, RenderSurfaceSize), new Vector3(0, 0, 0), new Vector3(0, 0, 0f), Color.White); spriteobject.End(); }
A sprite object also has its own Begin, Draw and End cycle. You can pass some SpriteFlags to the Begin method, which is very important if you don’t want to face huge performance problems. Our SpriteFlag indicates the render state for drawing our sprite needn’t be saved, which saves us from a huge overhead.
During the Drawing phase of the sprite, we can also set a transform renderstate (note that here we’re using the Fixed Function Pipeline again). This comes in handy, as our texture of 512x512 pixels would be bigger than our window.
Next we actually draw the texture using the sprite object. Of course we first need to pass the texture to draw from. The second argument is optional, but sometimes quite useful, so I’ll include it. It allows you to define which part of the texture to draw from: you can set the offset coordinate as well as the width and height of the region. Because we want to draw the whole texture, I’ve indicates to draw a rectangle of width and height 512, starting from coordinate (0,0).
The next argument indicates which pixel of the texture will be considered the center. It’s common practice to select the upper left point of the texture as its center. Then of course we need to indicate the screen position the center of where the texture will be drawn. Again, we indicate (0,0,0), so the texture will be drawn at the upper left corner of our screen. The last value is multiplied by every color and alpha value of the texture. So chosing white leaves all values the same, as they are all multiplied by 1.

Click here to go to the forum on this chapter!
Or click on one of the topics on this chapter to go there: How to get more precision Hi, your articles are tremendously usefull.
I w...Render to Texture
Hello,
I am trying to draw some primitive tr...Miss Spelling in this section
using (Sprite spriteobjec...
When you run this code, you should see our Shadow Map drawn at the upper left corner of the screen. Not a lot nicer than the result of last chapter, but you’ve learned a lot: you have drawn the scene into a texture, and drawn this 2D image to the screen afterwards!
Our HLSL code hasn’t been changed, so I’ll only list 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 Mesh Lamppost; private Material[] LamppostMaterials; private Texture[] LamppostTextures; private Mesh Car; private Material[] CarMaterials; private Texture[] CarTextures; private Matrix matView; private Matrix matProjection; private Matrix LightViewProjection; 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"); 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();
using (Sprite spriteobject = new Sprite(device)) { spriteobject.Begin(SpriteFlags.DoNotSaveState); spriteobject.Transform = Matrix.Scaling(0.4f, 0.4f, 0.4f); 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 UpdateLightData() { Vector3 LightPos = new Vector3(18, 2, 5); float LightPower = 0.7f; LightViewProjection = Matrix.LookAtLH(LightPos, new Vector3(2, 10, -3), new Vector3(0, 0, 1)) * Matrix.PerspectiveFovLH((float)Math.PI / 2, this.Width / this.Height, 1f, 100f); effect.SetValue("xLightPos", new Vector4(LightPos.X, LightPos.Y, LightPos.Z, 1)); effect.SetValue("xLightPower", LightPower); } private void DrawScene() { effect.SetValue("xWorldViewProjection", Matrix.Identity * matView * matProjection); effect.SetValue("xLightWorldViewProjection", Matrix.Identity * LightViewProjection); effect.SetValue("xRot", Matrix.Identity); effect.CommitChanges(); device.SetStreamSource(0, vb, 0); device.VertexDeclaration = vd; device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 16); 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.SetValue("xLightWorldViewProjection", LamppostWorld * LightViewProjection); effect.SetValue("xRot", Matrix.RotationX((float)Math.PI / 2)); 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); effect.SetValue("xLightWorldViewProjection", LamppostWorld * LightViewProjection); effect.SetValue("xRot", Matrix.RotationX((float)Math.PI / 2)); 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.SetValue("xLightWorldViewProjection", CarWorld * LightViewProjection); effect.SetValue("xRot", Matrix.RotationYawPitchRoll((float)Math.PI / 2, (float)Math.PI / 2, (float)Math.PI / 2) * Matrix.Translation(3, 15, 0f)); 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.SetValue("xLightWorldViewProjection", CarWorld * LightViewProjection); effect.SetValue("xRot", Matrix.RotationYawPitchRoll((float)Math.PI / 2, (float)Math.PI / 2, (float)Math.PI / 2) * Matrix.Translation(3, 15, 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(20, -17, 10); matProjection = Matrix.PerspectiveFovLH((float)Math.PI / 4, this.Width / this.Height, 0.3f, 200f); matView = Matrix.LookAtLH(CameraPos, new Vector3(0, 9, 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); } } } }
- Website design & XNA + DirectX code : Riemer Grootjans - ©2003 - 2011 Riemer Grootjans
|
|
|
|
|