|
|
|
|
Higher performance by using Triangle Strips -– Texture Mirroring revisited |
This chapter has nothing to do with HLSL – I’ve written it so people who are not following the Series can understand how to use triangle strips just by reading this chapter.
Up till now, we’ve only drawn a single triangle. This chapter we’ll expand our scene, so it’ll look a bit more like a street. I’ve divided the street into 5 parts: the road, the 2 sides of the pavement border, the pavement itself and the wall. 5 textured quads, which have to be drawn by 10 textured triangles.
To draw these 10 triangles, we could simply define 30 vertices, each holding their 3D position and 2D texture coordinate, which can be presented this way:

I’ve only put a few vertex numbers on the picture; otherwise it would be a mess. Every triangle has 3 vertices, and the vertices are all declared in a clockwise manner.
By looking at the image, I hope you notice almost all vertices are declared 2 or 3 times! This means a lot of redundancy in the information we send over to our AGP/PCIx slot, so there must be a way we can reduce the amount of vertices we send. For cases like this, where every triangle is sharing 2 vertices with the previous one, the TriangleStrip should be used. The idea is illustrated by the image below:

The idea behind TriangleStrips is that you should define each vertex only once. So for the first triangle, you have to define vertices 0,1 and 2. Now, for the next triangle, you only have to add vertex 3! DirectX will always use the last 3 vertices to draw the triangle, so for the second triangle it uses vertices 1, 2 and 3, which is correct.
For the fourth triangle, you only have to add vertex 4, and DirectX will use vertices 2,3 and 4. In a formula, the n-th triangle is defined by the (n-1)-th, the n-th and the (n+1)-th vertex, with n starting from 1. This way, you see the total amount of vertices has been decreased by a huge amount! Of course, this will yield much higher framerates when working with a larger number of triangles, such as our terrain of Series 1 (which could indeed also be defined using a TriangleStrip!).
There’s still one problem remaining. When you look at the red arrows, you’ll see it’s impossible to define all vertices in a clockwise manner around your triangles. This will always be the case, so when using a TriangleStrip, the rule is you switch your vertex definition from clockwise to counterclockwise and back every triangle.
As we’ll expand the number of triangles we’re storing in our vertex buffer, we have to indicate this as well at its initialization:
vb = new VertexBuffer(typeof(myownvertexformat), 12, device, Usage.WriteOnly, VertexFormats.Position | VertexFormats.Texture0, Pool.Managed);
Now we’re going to change the vertex definitions:
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);
As you can see, only 12 vertices are needed to define 10 triangles. You can notice I have used horizontal texture coordinates such as -0.25f and 1.25f. Because in our shader we set the AdressU and AdressV states to Mirror, these points are mapped to 0.25f and 0.75f respectively, which creates a mirrored view, as you can see in the image below. The same trick was used with the vertical coordinates, where the texture was mirrored 25 times! If we wouldn’t have mirrored the texture image, that small image would have been stretched over our whole street.

Nothing has changed to the kind of information contained in our vertices, so there’s no need to change the VertexDeclaration.
Before drawing, we’ll change the camera position, so we get a nicer view:
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)); }
Note that I’ve removed the device.Projection and device.View lines from this method, as they’re not needed any longer(we perform these transformations manually in the HLSL vertex shader).
I’ve also chosen black as my background color. Then the only thing you have to do is change this line in the OnPaint method:
device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 10);
Where we declare we’ll be drawing a TriangleStrip, made out of 10 triangles.
That’s it! This chapter you’ve learned another way to help you reduce bandwidth, and thus to increase your framerate.

Click here to go to the forum on this chapter!
Or click on one of the topics on this chapter to go there: Collision Detection Hi, I wonder how to make collision detection with ...Terrains - Manual Or Models I am currious to find out if terrains in games are...Something went wrong I'm doing this from C++ since there isn't one av...Texture Coords Hi Riemer,
Maybe a stupid question, but im afra...Triangle Strip Hi Riemer,
What are the pros and cons of using ...
The HLSL has remained unchanged, so I’m only going to 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 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 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"); } 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) device.SetTexture(0, meshtextures[i]); 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("xViewProjection", 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);
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); } } } }
- Website design & XNA + DirectX code : Riemer Grootjans - ©2003 - 2011 Riemer Grootjans
|
|
|
|
|