Visit The X-Zone


Table of Contents
--------------------------

1.0 : About This FAQ
   1.1: Is this FAQ available on the web in an updated form?
   1.2: Who is responsible for the Creation of this FAQ?
   1.3: Where can I address corrections or comments regarding this FAQ?
   1.4: Are there other FAQs that address DirectX development questions?
   1.5: What changes have been made since the last posted version of this FAQ?

2.0 : Using the Newsgroups
   2.1: The microsoft.public.win32.programmer.directx.graphics Newsgroup
   2.2: What type of messages should be posted to this newsgroup?
   2.3: Where should I post questions about ----- ?
   2.4: What steps should I take before starting a new thread in this newsgroup?
   2.5: What information should I include about my application when posting a problem?
   2.6: What is a Microsoft MVP? Are they employees of Microsoft?

3.0 : The DirectX SDK
   3.1: Where can I download the latest released version of the DirectX SDK?
   3.2: Can I order the DirectX SDK on CD from Microsoft?
   3.3: I found that the DirectX SDK is available as part of the Microsoft Platform SDK. Is this the current version?

4.0 : DirectX 9 Graphics
   4.1: How can I determine what assembly level shader code is generated from HLSL shader code in my effect file?

5.0 : Compiler Issues
   5.1: After installing the DX 8 SDK, I receive the error LNK1104: Cannot Open File "d3dim.lib" when attempting to compile my
      program.
   5.2: I have heard that DirectX 8.1 no longer supports Windows 95. Can I compile applications compatible with Windows 95 if I
      have the DirectX 8.1 SDK installed?
   5.3: Will applications that I compile with the DirectX 8.1 SDK be compatible with systems with the DirectX 8.0 runtimes?
   5.4: Why doesn't Intellisense offer code completion options for DX 8 interfaces under VC++?
   5.5: I'm having problems with the Borland compiler and Direct3D. How can I fix them?

6.0 : Troubleshooting
   6.1: Why are my primitives rendered as black when I render primitives with pre-lit vertices?
   6.2: How can I get debugging information from Direct3D?
   6.3: My Direct3D / DirectX Graphics application compiles and runs, but the entire viewport is black.
   6.4: The debugger is showing Direct3D8 errors stating that memory is still allocated. How can I track down the source of
      these problems?
   6.5: Why does my DX 8.1 application cause the display to flash between bright green or purple?

7.0 : Device Creation
   7.1: How can I render to multiple windows under DirectX 8 Graphics?
   7.2: Why do my calls to IDirect3DDevice8::Getxxxx fail?
   7.3: Why does IDirect3DDevice8::CreateRenderTarget() return an error when I try to create a multisample render target with
      the Lockable flag set?

8.0 : Performance Optimization
   8.1: I am rendering polygons while traversing my scene using a spatial subdivision technique (e.g. a BSP Tree), and my frame
      rates are far lower than they are if I simply render the scene. Why is this?
   8.2: Why do I get a much slower frame rate (often 60FPS) when I run in full screen mode than I do in windowed mode?

9.0 : Rendering Primitives
   9.1: How can I render lines in Direct3D that have a specific width in world space?

10.0 : Depth Buffering
   10.1: Why does my app fail to perform proper depth buffering when I use a W buffer, even though it works properly when using
      Z-buffering?
   10.2: Why does W-buffering fail with my pre-transformed vertices or my programmable vertex shader?
   10.3: The scene in my Direct3D application will not render if I enable depth buffering

11.0 : 2D Graphics
   11.1: Can I perform 2D operations in DirectX 8 Graphics?
   11.2: How can I perform color keying with DirectX Graphics?

12.0 : Textures
   12.1: How can I render video to a texture in DirectX 8 Graphics?
   12.2: How do you determine the total texture memory a card has, excluding AGP memory?

13.0 : Accessing Surface Memory
   13.1: How can I save the contents of a surface or texture to a file?

14.0 : Texture Blending Stages
   14.1: I am rendering alpha blended polygons and setting the alpha of the diffuse vertex component to determine the opacity.
      It works when there is no texture set, but as soon as I set a texture the alpha that I set is no longer applied. Why?

15.0 : D3DX Mesh Classes
   15.1: Why does rendering of an ID3DXMesh object slow down significantly after I define subsets?
   15.2: The adjacency array generated for a D3DX Mesh has three entries per face, but some faces may not have adjacent faces on
      all three edges. How is this encoded?

16.0 : D3DX Sprite Classes
   16.1: When I draw an image using ID3DXSprite::Draw() with 1:1 scaling, the sprite is different than the original image size.
      Why?

17.0 : D3D Lighting
   17.1: When I set a world matrix with scaling, my lighting seems to change. What is happening, and how can I prevent this?

18.0 : Programmable Vertex Shaders
   18.1: Why does creation of a programmable vertex shader in my application fail on certain hardware?

19.0 : 3D Transformations
   19.1: How can I find the screen coordinates of a location in object space?
   19.2: How can I transform screen coordinates to world or object space?
   19.3: How can I extend the Pick sample to select objects with a World transformation?

20.0 : D3DX Texture Functions
   20.1: When loading a texture with the D3DX texture creation functions I specify a color key, but no transparency appears when
      I render the image.

21.0 : DirectDraw
   21.1: After either using a helper function to load an image to a surface, or calling GetDC()on a surface and subsequently
      calling ReleaseDC() on the same surface, I find that there is an additional GDI handle held by my application. Is this
      a leak?

22.0 : Content Creation
   22.1: How can I create .x files that can be used with Direct3D?
   22.2: How do I create compressed textures?
   22.3: Where can I find free 3d models and textures?

------------------------------------------------------------------------------
Section 1 : About This FAQ
------------------------------------------------------------------------------

1.1: Is this FAQ available on the web in an updated form?

The latest version of this FAQ is maintained at:

http://www.mvps.org/directx/faq.php
          --------------------------
1.2: Who is responsible for the Creation of this FAQ?

This FAQ was originally created by Microsoft DirectX MVP Robert Dunlop, in collaboration with:

Rich Thomson
Microsoft Direct3D / Windows Installer MVP
http://www.xmission.com/~legalize/book/

Eric DeBrosse
Microsoft Visual Basic DirectX MVP
http://www.mvps.org/vbdx/

          --------------------------
1.3: Where can I address corrections or comments regarding this FAQ?

These can be addressed to rdunlop@mvps.org. Note that due to the high volume of mail received we cannot guarantee a reply, but we will do our best to act upon your comments and suggestions.
          --------------------------
1.4: Are there other FAQs that address DirectX development questions?

Yes, Microsoft maintains the following FAQs for DirectX developers:

Microsoft DirectX 8 Developer FAQ
http://msdn.microsoft.com/library/en-us/dndxgen/html/directx8faq.asp

Microsoft DirectX 7 Developer FAQ
http://msdn.microsoft.com/library/en-us/dndxgen/html/dxfaq2.asp
          --------------------------
1.5: What changes have been made since the last posted version of this FAQ?

The following changes have been made since Version: 1.0, originally posted to the newsgroup on April 11, 2002:

* Added Section 2.6: What is a Microsoft MVP? Are they employees of Microsoft?
* Added link to rules of conduct for Microsoft newsgroups in Section 2.2
* Added Section 6.4 on tracking memory leaks by AllocID in DirectX Graphics
* New Category for Performance Optimization
* Added Section 8.1 on caching of numerous small polygons into larger batches

Additions for Version 1.02, posted June 10, 2002:

* Added Section 7.3 on errors creating lockable multisample rendertargets
* Added Section 6.5 on reason for display of alternating green and purple background
* Added Section 3.1, Section 3.2, and Section 3.3 explaining where and how to get the latest version of the DirectX SDK

Additions for Version 1.03, Posted July 17, 2002:

* Added Section 8.2 on reason for full screen mode running slower than windowed

Additions for Version 1.04, Posted August 31, 2002:

* Added Section 9.1 on rendering lines of varying width
* Added Section 15.2 on ID3DXMesh adjacency entries for edges with no adjacent faces

Additions for Version 1.05, Posted October 19, 2002:

* Added Section 21.1 regarding cached HBITMAP handles after GetDC() call on surface

Additions for Version 1.06, Posting date TBD:

* New section for DirectX 9 Graphics
* Added Section 4.1 showing how to view assembly code generated from HLSL
------------------------------------------------------------------------------
Section 2 : Using the Newsgroups
------------------------------------------------------------------------------

2.1: The microsoft.public.win32.programmer.directx.graphics Newsgroup

Welcome to microsoft.public.win32.programmer.directx.graphics!

The purpose of this newsgroup is to discuss programming questions and issues related to DirectX graphics.
          --------------------------
2.2: What type of messages should be posted to this newsgroup?

Messages posted here should relate directly to the development of applications that utilize DirectX Graphics, Direct3D, or DirectDraw.

Posts should be in text format, and should not have large attachments included. If it is necessary for others to look at screen shots, test applications, etc, place them on a website and include a link to the content in your post.

Types of messages that should not be posted here:
        End user installation or compatability issues
        Messages regarding beta versions of DirectX
        Issues regarding other APIs not listed above
        Advertisements
        Inflammatory remarks, aka "Flame"
        Job postings (use misc.jobs.* instead)

For additional guidelines on the rules of conduct for the Microsoft public newsgroups go to:

http://support.microsoft.com/support/news/rules.asp
          --------------------------
2.3: Where should I post questions about ----- ?

DirectX graphics End user issues:
   microsoft.public.directx.graphics
Using DirectX in Visual Basic:
   microsoft.public.vb.directx
DirectShow issues:
   microsoft.public.win32.programmer.directx.video
DirectSound, DirectMusic, and DirectX Audio issues:
   microsoft.public.win32.programmer.directx.audio
DirectInput issues:
   microsoft.public.win32.programmer.directx.input
DirectPlay issues:
   microsoft.public.win32.programmer.directx.networking
DirectPlay issues on PocketPC:
   microsoft.public.pocketpc.developer.networking

For questions relating to graphics algorithms that are not DirectX specific, the following third party public forums should be considered:
   comp.graphics.algorithms
   comp.games.development.programming.algorithms

          --------------------------
2.4: What steps should I take before starting a new thread in this newsgroup?

Prior to submitting a development problem to the newsgroup, please make sure that you have explored your troubleshooting options and gathered as much information about the problem as you can to provide in the post. These options include:

1. Run the application with debug output set to maximum, and see if the debug output is helpful in finding the problem (see Section 6.2). When posting, include any output from the debugger.

2. Test the application with the reference rasterizer, to see if the problem occurs there as well. If it does not occur under the reference rasterizer, then the problem is driver related, check to be sure that you have the latest drivers. Report it to the manufacturer if the problem persists.

3. Make sure that you are checking all returned HRESULT values for failure.

4. Check to be sure that you are running the latest drivers.

5. Check to be see if your question has already been answered previously in the newsgroup archives, in this FAQ, or in the Microsoft DirectX Developer FAQ. (http://groups.google.com/ is a great way to search the Usenet discussion forums.)

          --------------------------
2.5: What information should I include about my application when posting a problem?

In order to receive a meaningful response regarding your development issue, it is important to provide sufficient background information. In general, this includes:

What version of DirectX interfaces are you using?
What compiler are you using?
What operating system(s) is the problem occurring on?
What video adapter(s) are you testing on?
Are there any messages returned by the Debug Runtimes? (see Section 6.2)

In addition to this information, you may consider including sections of your source code that may be applicable to the problem. If you do include source code, trim it down to those sections of code that directly relate to the problem.
          --------------------------
2.6: What is a Microsoft MVP? Are they employees of Microsoft?

The MVP Award, which stands for "Most Valuable Professional" is an annual award given to outstanding members of Microsoft's peer-to-peer communities. The MVP program recognizes individuals who provide a high level of accurate support to the on-line community.

Participants in the Microsoft MVP program are not employees of Microsoft, and receive no monetary compensation for these services. The time that they provide to support Microsoft products is strictly voluntary.
------------------------------------------------------------------------------
Section 3 : The DirectX SDK
------------------------------------------------------------------------------

3.1: Where can I download the latest released version of the DirectX SDK?

The latest released version of the DirectX SDK can be found in the download section at:

http://msdn.microsoft.com/directx/
          --------------------------
3.2: Can I order the DirectX SDK on CD from Microsoft?

No, at this time a CD containing the DirectX SDK is not available for order. Universal MSDN subscribers will however receive the Microsoft SDK as part of their subscription.
          --------------------------
3.3: I found that the DirectX SDK is available as part of the Microsoft Platform SDK. Is this the current version?

The Platform SDK is released periodically, and thus can often lag behind the current released SDKs. With the rapid changes in gaming hardware and capabilities, updates for DirectX often are available that are not included in the Platform SDK. Always go to the DirectX site on MSDN, at:

http://msdn.microsoft.com/directx/
------------------------------------------------------------------------------
Section 4 : DirectX 9 Graphics
------------------------------------------------------------------------------

4.1: How can I determine what assembly level shader code is generated from HLSL shader code in my effect file?

You can make use of the command line effect compiler, fxc.exe, provided in the \bin\dxutils subdirectory of the SDK installation. Using the /Fc switch will cause a source code listing to be generated. For example, the command

c:\dxsdk\bin\dxutils\fxc /FcListing.txt MyHlsl.fx

will compile the effect file MyHlsl.fx, and create a source code listing as /FcListing.txt.
------------------------------------------------------------------------------
Section 5 : Compiler Issues
------------------------------------------------------------------------------

5.1: After installing the DX 8 SDK, I receive the error LNK1104: Cannot Open File "d3dim.lib" when attempting to compile my program.

This is because the library for Direct3D Immediate Mode (now called DirectX Graphics) has been renamed as D3D8.LIB. To correct this, link to D3D8.LIB instead of D3DIM.LIB.
          --------------------------
5.2: I have heard that DirectX 8.1 no longer supports Windows 95. Can I compile applications compatible with Windows 95 if I have the DirectX 8.1 SDK installed?

This is correct. If you wish to compile applications under the 8.1 SDK that are compatible with Windows 95, see Section 5.3 for instructions on compiling an application with the DirectX 8.1 SDK that will use the DirectX 8.0 interfaces.
          --------------------------
5.3: Will applications that I compile with the DirectX 8.1 SDK be compatible with systems with the DirectX 8.0 runtimes?

By default, applications compiled under 8.1 will require the 8.1 runtimes to run, because some of the interfaces have changed and have different GUIDs. However, you can specify a constant when creating the Direct3D object that will use the 8.0 interfaces. Rather than creating an object as shown in the docs with

g_pD3D=Direct3DCreate8(D3D_SDK_VERSION);

instead use

g_pD3D=Direct3DCreate8(120);

The value 120 is equal to the D3D_SDK_VERSION that was specified in the DirectX 8.0 headers, which has been changed in the 8.1 SDK. Specifying the original value will cause 8.0 version interfaces to be used by Direct3D, providing compatibility with 8.0. Note that new features in 8.1, such as the latest pixel shader versions (1.2 - 1.4), will not be available.

Visual Basic Note: Developing with the 8.0 interfaces in VB when DX 8.1 has been installed can be done. Instead of referencing the DX8VB.DLL type library found in the \WINDOWS\SYSTEM folder, you could add a reference to the older 8.0 type library. Place a copy of the older DX8VB.DLL in your project folder, rather than replacing the original file.

          --------------------------
5.4: Why doesn't Intellisense offer code completion options for DX 8 interfaces under VC++?

The problem is that the IDE is drawing its information from the older headers that were installed with VC++. It will also use information from the headers in your project files, though simply using #include does not cause them to be inventoried from the new headers. You can enable Intellisense with the new interface by adding the header files containing the definitions to your project (e.g. D3DX8.H and D3D8.H for Direct3D). Right click on your project in the FileView pane, select "Add Files to Project...", then select the necessary include files from the DXSDK\INCLUDE\ directory.

Note that Intellisense works properly with the DirectX 8.x interfaces in Visual Studio .NET
          --------------------------
5.5: I'm having problems with the Borland compiler and Direct3D. How can I fix them?

Borland compilers don't use the same object file format as MS compilers. For the Direct3D core functionality, this is not a
problem as you simply need to create an import library for d3d8.dll. However, D3DX is provided as a static library only in MS compiler object format. To use D3DX from the Borland compiler, you must wrap the static library in a DLL and create an import library for the DLL. Michael Foetsch has code that does this.

See http://www.geocities.com/foetsch/cbuilder.htm

Also, unless Borland has changed their fp support, don't forget this if you use Borland...(you will find it in the old DirectX SDK docs)

Borland Floating-Point Initialization

Compilers from Borland report floating-point exceptions in a manner that is incompatible with Microsoft® Direct3D®. To solve this problem, include a _matherr exception handler like the following:

// Borland floating point initialization
#include
#include

void initfp(void)
{
// Disable floating point exceptions.
_control87(MCW_EM,MCW_EM);
}

int _matherr(struct _exception *)
{
return 1; // Error has been handled.
}

------------------------------------------------------------------------------
Section 6 : Troubleshooting
------------------------------------------------------------------------------

6.1: Why are my primitives rendered as black when I render primitives with pre-lit vertices?

In Direct3D lighting is turned on by default, and will attempt to calculate lighting values for each vertex. Because pre-lit vertices do not have a normal, the lighting engine automatically outputs a color of 0 when rendering your pre-lit vertices, even though the vertex format provided a color. To prevent this, you must set D3DRS_LIGHTING to FALSE prior to rendering pre-lit vertices.

If you use a D3DFVF_XYZRHW position component, no vertex processing is applied to the vertices and they will be lit with the diffuse and specular vertex components.
          --------------------------
6.2: How can I get debugging information from Direct3D?

To do this, you must first be running the debug versions of the runtimes, if they are not installed you will have to do this first.

Next, go into the DirectX control panel, and open the Direct3D tab. Select "Use Debug Version of Direct3D", and adjust the Debug Output Level slider all the way to "More".

If you are using D3DX, make sure you are linking with the debug (d3dx8d.lib or d3dx8dt.lib) version of the library included with the SDK. Note that d3dx8dt.lib is an import library for a DLL. You cannot redistribute this DLL with your application, you must link your program with the static release library for distribution.

Finally, execute a debug build from the VC++ IDE (use F5 to execute with debugging enabled, not ctrl-F5). Debugging messages will appear in the output window.

Visual Basic Note: VB users running Win2K or XP can capture debug output from DX using DBMON.EXE included with the SDK. Under Win2K you must have administrator privileges for DBMON.EXE to work. If you are using Win98 or WinMe you can use a tool like DebugView, download it for free here: http://www.sysinternals.com

          --------------------------
6.3: My Direct3D / DirectX Graphics application compiles and runs, but the entire viewport is black.

There are any number of reasons why this may occur. Here are some quick checks that can be performed, which will catch several common scenarios:

1. Clear your scene to a different background color, something with a high contrast to the current color used when calling IDirect3DDevice8::Clear(). This will allow you to determine if objects are being rendered to the scene, but are not visible because they are the same color as the background. Common scenarios include objects being rendered as black because they are not lit, or objects rendered in the current fog color when the background color is the same as that set for fog.

2. Turn culling off by setting D3DRS_CULLMODE to D3DRS_CULLNONE. This will allow objects which have a reverse winding order to be displayed.

3. Disable depth buffer occlusion by setting D3DRS_ZENABLE to D3DZB_FALSE. This will allow objects that are failing the depth test to be displayed. If this causes the objects to become visible, check to make sure that you are clearing the depth buffer by including the D3DCLEAR_ZBUFFER flag when calling IDirect3DDevice8::Clear().

4. Set the fill mode to wireframe, by setting D3DRS_FILLMODE to D3DFILL_WIREFRAME. In combination with disabling depth buffering, this will help to determine if the scene is being occluded by a primitive that is being rendered in the foreground and occluding the rest of the scene.
          --------------------------
6.4: The debugger is showing Direct3D8 errors stating that memory is still allocated. How can I track down the source of these problems?

When debugging you may see errors such as these reported during application shutdown:

Direct3D8: (INFO) :MemFini!
Direct3D8: (ERROR) :Memory still allocated! Alloc count = 181
Direct3D8: (ERROR) :Current Process (pid) = 000000c8
Direct3D8: (ERROR) :Memory Address: 018eeebc lAllocID=135 dwSize=00000040, ReturnAddr=00bc8f7e (pid=000000c8)

This indicates that there were objects allocated under DirectX Graphics that were not released during program termination, as one or more objects are still holding a reference count. This geneally means that somewhere in the application a call has been made that increments the reference count of an object, without a matching Release() being performed to decrement the reference count when it is no longer used.

To determine what objects are involved, you can use the AllocID shown for each object to locate the code that initially allocated each object. To do this, go to the Direct3D tab of the DirectX control panel and enter the AllocID in the "Break On AllocID" field, and apply the change. Run a debug build of the application from the VC++ IDE, and the debugger will break into the program at the point of allocation with the specified AllocID.
          --------------------------
6.5: Why does my DX 8.1 application cause the display to flash between bright green or purple?

This can happen for a couple of reasons:

1. The debug runtimes are encountering a critical error that prevents rendering of the scene. Check the debug output, as described in Section 6.2.

2. When you are using the D3DSWAPEFFECT_DISCARD method for presentation with the debug runtimes, and nothing is being drawn to the frame buffer between between calls to Present(). As this method does not guarantee the contents of the frame buffer, the debug runtimes fill the back buffers with a solid color to indicate undrawn areas.
------------------------------------------------------------------------------
Section 7 : Device Creation
------------------------------------------------------------------------------

7.1: How can I render to multiple windows under DirectX 8 Graphics?

The recommended way to render to multiple windows within the same process is to generate separate back buffers for each window. This is supported under DirectX Graphics through the IDirect3DSwapChain interface.

Use the IDirect3DDevice8::CreateAdditionalSwapChain() function to create a swap chain for each new window. To render to a window, first set the render target to point to the back buffer of the window's swap chain using IDirect3DDevice8::SetRenderTarget(), then render the scene and call the IDirect3DSwapChain::Present() method of the window's swap chain.

Further information on using swap chains to present to multiple windows can be found in this article:

http://www.mvps.org/directx/articles/rendering_to_multiple_windows.htm

Creating a swap chain per-window can easily exhaust available video memory with multiple overlapping windows. In these cases you might want to create a single back buffer that is the size of the screen, restrict rendering using the viewport, and use the window and RECT parameters of Present to present from the single back buffer to any number of windows.
          --------------------------
7.2: Why do my calls to IDirect3DDevice8::Getxxxx fail?

This occurs when you have created a device with the D3DCREATE_PUREDEVICE behavior flag. Such a device does not allow you to read any of the render states that can be stored in a state block.

Supported
---------
GetAvailableTextureMem
GetBackBuffer
GetDesc
GetCreationParameters
GetDepthStencilSurface
GetDeviceCaps
GetDirect3D
GetDisplayMode
GetFrontBuffer
GetRasterStatus
GetCurrentTexturePalette
GetIndices
GetPaletteEntries
GetRenderTarget
GetStreamSource
GetTexture

Not Supported
-------------
GetClipPlane
GetClipStatus
GetLight
GetLightEnable
GetMaterial
GetPixelShader
GetPixelShaderConstant
GetRenderState
GetTextureStageState
GetTransform
GetVertexShader
GetVertexShaderConstant
GetViewport

          --------------------------
7.3: Why does IDirect3DDevice8::CreateRenderTarget() return an error when I try to create a multisample render target with the Lockable flag set?

Multisample render targets cannot be locked. Thus the Lockable flag can only be set when the multisample type is D3DMULTISAMPLE_NONE.
------------------------------------------------------------------------------
Section 8 : Performance Optimization
------------------------------------------------------------------------------

8.1: I am rendering polygons while traversing my scene using a spatial subdivision technique (e.g. a BSP Tree), and my frame rates are far lower than they are if I simply render the scene. Why is this?

You are probably rendering each polygon as a separate DrawPrimitive call, resulting in a large number of drawing calls using very small batches of vertices. This leads to poor performance in DirectX, and is a common pitfall.

Rather than rendering each polygon as it is encountered, your application should batch them together and render larger groups of polygons, preferably at least 200-300 vertices at a time. A simple class demonstrating the caching of polygons can be found here:

http://www.mvps.org/directx/articles/vcache.htm

Note that this shows a fairly simplistic implementation. In a scene with multiple textures and render states you will want to perform some form of sorting to minimize the number of state changes.
          --------------------------
8.2: Why do I get a much slower frame rate (often 60FPS) when I run in full screen mode than I do in windowed mode?

This is because the full screen device is configured to synchronize presentation to the vertical blanking period, which causes the frame rate to be limited to the refresh rate of the monitor. This can be set when calling IDirect3D8::CreateDevice(). See the documentation for D3DPRESENT_PARAMETERS for details.
------------------------------------------------------------------------------
Section 9 : Rendering Primitives
------------------------------------------------------------------------------

9.1: How can I render lines in Direct3D that have a specific width in world space?

Direct3D does not support lines of varying thickness, all line primitives are rendered as single pixel lines regardless of distance from viewer. To generate lines of differing thickness requires converting them to screen aligned quads. Take a cross product of the linedirection and the forward vector from your view matrix (viewMat._13,viewMat._23,viewMat._33), providing a vector perpendicular to the line and parallel to the screen. Then scale this to your line width and use it to offset the ends of your line in either direction to form a quad.
------------------------------------------------------------------------------
Section 10 : Depth Buffering
------------------------------------------------------------------------------

10.1: Why does my app fail to perform proper depth buffering when I use a W buffer, even though it works properly when using Z-buffering?

To use w-buffering in DirectX, the projection matrix must have a fourth column equal to [0 0 1 0]. For further information, see "A W-Friendly Projection Matrix" in the DirectX SDK documentation.
          --------------------------
10.2: Why does W-buffering fail with my pre-transformed vertices or my programmable vertex shader?

This often occurs because programs relying on vertex shaders may not bother to set transformation matrices, because they are performing the transformation themselves. However, for W-buffering to work properly, a compliant projection matrix must be set prior to rendering. For more information, see "A W-Friendly Projection Matrix" in the DirectX SDK documentation.
          --------------------------
10.3: The scene in my Direct3D application will not render if I enable depth buffering

This is often caused by failing to clear the depth buffer prior to rendering. Be sure to use the D3DCLEAR_ZBUFFER flag when calling the IDirect3DDevice[x]::Clear() function, and set the Z parameter to 1.0 so that the depth buffer is clear to the maximum allowable Z value.
------------------------------------------------------------------------------
Section 11 : 2D Graphics
------------------------------------------------------------------------------

11.1: Can I perform 2D operations in DirectX 8 Graphics?

Microsoft merged both DirectDraw and Direct3D into one component called "DirectX Graphics". Either continue to use DirectDraw 7 or use the newer 3D interfaces. Using Direct3D for your 2D graphics allows for hardware-accelerated rotation, scaling, etc.

There are several methods that can be used to render 2D images under DirectX Graphics, including:

1. Using pre-transformed/pre-lit vertices to render a textured quad. An article on this technique can be found at:

http://www.mvps.org/directx/articles/blit3d.htm

2. Retrieving the back buffer surface with IDirect3DDevice8::GetBackBuffer() then using IDirect3DDevice8::CopyRects() to copy an image surface to the back buffer.

3. Create an instance of ID3DXSprite and use the ID3DXSprite::Draw() or ID3DXSprite::DrawTransform() methods to render a texture to a quad.
          --------------------------
11.2: How can I perform color keying with DirectX Graphics?

Color keying is not directly supported, instead you will have to use alpha blending to emulate color keying.

The D3DXCreateTextureFromFileEx() function can be used to facilitate this. This function accepts a key color parameter, and will replace all pixels from the source image containing the specified color with transparent black pixels in the created texture.
------------------------------------------------------------------------------
Section 12 : Textures
------------------------------------------------------------------------------

12.1: How can I render video to a texture in DirectX 8 Graphics?

See the DirectShow Texture3D sample located in the directory
%DX8SDK%\samples\Multimedia\DirectShow\Players\Texture3D
          --------------------------
12.2: How do you determine the total texture memory a card has, excluding AGP memory?

IDirect3DDevice8::GetAvailableTextureMem returns the total available memory, including AGP. Allocating resources based on an assumption of how much video memory you have is not a great idea. For example, what if the card is able to compress the textures? There might be more space available than you might have thought. You should create resources and check for 'out of memory' errors, then scale back on the textures. For example, you could remove the top mip-levels of your textures.

------------------------------------------------------------------------------
Section 13 : Accessing Surface Memory
------------------------------------------------------------------------------

13.1: How can I save the contents of a surface or texture to a file?

The DirectX 8.1 SDK added two functions to the D3DX library specifically for this purpose: D3DXSaveSurfaceToFile() and D3DXSaveTextureToFile(). These functions support saving an image to file in either BMP or DDS format.

In previous versions you will have to lock the surface and read the image data, then write it to a bitmap file. An article on writing a function to store bitmaps can be found at:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdi/bitmaps_7zfp.asp

Alternatively, GDI+ could be used to save the image in a wide variety of formats, though this requires additional support files to be distributed with your application.
------------------------------------------------------------------------------
Section 14 : Texture Blending Stages
------------------------------------------------------------------------------

14.1: I am rendering alpha blended polygons and setting the alpha of the diffuse vertex component to determine the opacity. It works when there is no texture set, but as soon as I set a texture the alpha that I set is no longer applied. Why?

The problem originates in the texture blending stages, rather than in the subsequent alpha blending. Alpha can come from several possible sources. If this has not been specified, then the alpha will be taken from the texture, if one is selected. If no texture is selected, then the default will use the alpha channel of the diffuse vertex component.

Explicitly specifying the diffuse vertex component as the source for alpha will insure that the alpha is drawn from the alpha value you set, whether a texture is selected or not:

pDevice->SetTextureStageState(D3DTSS_ALPHAOP,D3DTOP_SELECTARG1);
pDevice->SetTextureStageState(D3DTSS_ALPHAARG1,D3DTA_DIFFUSE);

If you later need to use the texture alpha as the source, set D3DTSS_ALPHAARG1 to D3DTA_TEXTURE.

------------------------------------------------------------------------------
Section 15 : D3DX Mesh Classes
------------------------------------------------------------------------------

15.1: Why does rendering of an ID3DXMesh object slow down significantly after I define subsets?

You probably have not optimized the mesh after defining the face attributes. If you specify attributes and then call ID3DXMesh::DrawSubset(), this method must perform a search of the mesh for all faces containing the requested attributes. In addition, the rendered faces are likely in a random access pattern, thus not utilizing vertex cache. After defining the face attributes for your subsets, call the ID3DXMesh::Optimize or ID3DXMesh::OptimizeInPlace methods and specifying an optimization method of D3DXMESHOPT_ATTRSORT or stronger. Note that for optimum performance you should optimize with the D3DXMESHOPT_VERTEXCACHE flag, which will also reorder vertices for optimum vertex cache utilization.
          --------------------------
15.2: The adjacency array generated for a D3DX Mesh has three entries per face, but some faces may not have adjacent faces on all three edges. How is this encoded?

Entries where there are no adjacent face are encoded as 0xffffffff.
------------------------------------------------------------------------------
Section 16 : D3DX Sprite Classes
------------------------------------------------------------------------------

16.1: When I draw an image using ID3DXSprite::Draw() with 1:1 scaling, the sprite is different than the original image size. Why?

Since the image file is loaded into a texture, the bitmap is scaled to match the capabilities of the hardware. In general, this means that images that have dimensions that are not powers of 2 will be scaled up to the nearest power of 2.

When loading an image with D3DXCreateTextureFromFileEx(), you can pass a pointer to a D3DXIMAGE_INFO structure, which will be filled with information about the source image. You can then get the size of the texture using IDirect3DTexture::GetLevelDesc() and calculate the required scaling factor for 1:1 rendering:

LPDIRECT3DTEXTURE8 pText;
D3DXIMAGE_INFO info;
D3DXCreateTextureFromFileEx(....,&info,....,&pText);
D3DSURFACE_DESC desc;
pText->GetLevelDesc(0,&desc);
D3DXVECTOR2 vScaling;
vScaling.x=info.Width/desc.Width;
vScaling.y=info.Height/desc.Height;
------------------------------------------------------------------------------
Section 17 : D3D Lighting
------------------------------------------------------------------------------

17.1: When I set a world matrix with scaling, my lighting seems to change. What is happening, and how can I prevent this?

The world matrix is applied to both the coordinates and normals of vertices. If the world matrix includes a scaling factor, this will change the magnitude of the vertex normals and effect lighting. To prevent this, set the D3DRS_NORMALIZENORMALS render state to TRUE. This will re-normalize the vertex normals after transformation.
------------------------------------------------------------------------------
Section 18 : Programmable Vertex Shaders
------------------------------------------------------------------------------

18.1: Why does creation of a programmable vertex shader in my application fail on certain hardware?

This may occur when the usage flag specified to IDirect3DDevice8::CreateVertexShader() does not match the vertex processing behavior of the device. Be sure that the usage flag is set to D3DUSAGE_SOFTWAREPROCESSING if the device was create with D3DCREATE_SOFTWARE_VERTEXPROCESSING set, or 0 if the device was created with the D3DCREATE_HARDWARE_VERTEXPROCESSING. Devices supporting mixed mode (D3DCREATE_MIXED_VERTEXPROCESSING) can create shaders with either usage, but the usage flag must match the mode that will be used when rendering with the shader.

This can also occur when the device uses hardware vertex processing but the hardware does not support a sufficient shader version as specified in your shader. Check the VertexShaderVersion member of D3DCAPS8 to verify this against your requirements before selecting a device. For example, if you are implementing a vertex shader that requires Version 1.0 support, you would add the following to the ConfirmDevice() code (assuming you are using the D3DApp framework):

if( (dwBehavior & D3DCREATE_HARDWARE_VERTEXPROCESSING ) ||
(dwBehavior & D3DCREATE_MIXED_VERTEXPROCESSING ) )
{
if( pCaps->VertexShaderVersion < D3DVS_VERSION(1,0) )
return E_FAIL;
}

You do not need to perform this check on devices using software vertex processing, as shader support is guaranteed through emulation.

------------------------------------------------------------------------------
Section 19 : 3D Transformations
------------------------------------------------------------------------------

19.1: How can I find the screen coordinates of a location in object space?

This can be performed using the D3DXVec3Project() function provided in the D3DX libraries. To perform this transformation manually:

1. Transform the object space coordinate by the world, view, and projection matrices, resulting in a 4D vector X,Y,Z,W.
2. Divide X,Y,Z,1 by W to arrive at x',y',z',rhw.
3. Scale x' and y' to the coordinate system of the viewport, by calculating 0.5*(1.0+x,1.0+y)*(width,height)+(top,left).
          --------------------------
19.2: How can I transform screen coordinates to world or object space?

A screen coordinate does not actually equate to a single location in world space. More correctly, it can be represented as a line segment drawn through the viewing frustum, bounded by corresponding points on the near and far clipping planes. To find single point in world space along this segment, a depth is required, which is often derived from the scene by finding the nearest intersection of this line segment with rendered primitives.

Here are several resources that should be helpful in performing this operation:

1. The D3DXVec3Unproject function can be used to transform a point in screen space with a given depth to object space, using specified transformation matrices and viewport. Calling this function twice with depths of 0.0 and 1.0 will define the line segment within the viewing frustum. Note that this function can alternately be used to transform to world space by specifying an identity matrix for the world transformation.

2. An example of transforming screen coordinates to world space and performing intersection testing in world space can be found in the Pick sample in the DirectX 8.1 SDK.

3. A similar example that allows for objects with differing world transformations by first converting the screen coordinates to a segment in world space, then back transforming them to object space for each object, can be found at:

http://www.mvps.org/directx/articles/improved_ray_picking.htm
          --------------------------
19.3: How can I extend the Pick sample to select objects with a World transformation?

To allow for world matrix transformations, the ray needs to be back-transformed into model space for each object. A demo of this technique, with sample code, can be found at:

http://www.mvps.org/directx/articles/improved_ray_picking.htm
------------------------------------------------------------------------------
Section 20 : D3DX Texture Functions
------------------------------------------------------------------------------

20.1: When loading a texture with the D3DX texture creation functions I specify a color key, but no transparency appears when I render the image.

This is often caused by specifying a key color that does not have opaque alpha. Pixels read from a file without an alpha channel are assumed to be opaque (alpha of 255), so comparison with a key color with an alpha other than 255 will automatically fail. You can readily check to see if this is the problem by ORing your key color with 0xff000000.
------------------------------------------------------------------------------
Section 21 : DirectDraw
------------------------------------------------------------------------------

21.1: After either using a helper function to load an image to a surface, or calling GetDC()on a surface and subsequently calling ReleaseDC() on the same surface, I find that there is an additional GDI handle held by my application. Is this a leak?

An increase of one GDI handle is normal after the first time you retrieve and release a surface, this behavior is by design. This should only happen on the first call to GetDC for a given surface. When you call GetDC the first time a bitmap handle is associated with the surface memory as well as a DC, into which the HBITMAP is selected. Calling ReleaseDC() releases the DC, but the bitmap handle is cached to speed up subsequent calls to GetDC(). The bitmap handle is released automatically during the final release of the surface.

If you are loading a large number of images and are concerned about the large number of handles that will be created, you can load each image onto a temporary surface and then blit the image from the temporary surface to the target surface. When finished loading images the temporary surface can be released, and there will be no HBITMAP handles cached in the image surfaces assuming no call to GetDC() is made on them.
------------------------------------------------------------------------------
Section 22 : Content Creation
------------------------------------------------------------------------------

22.1: How can I create .x files that can be used with Direct3D?

The DirectX SDK 'Extras' download contains GUI based exporters with source code. The exporters can export patch, keyframe and skinning information. There are currently plug-ins for 3DStudio Max 3.0, 3DStudio Max 4.0, Maya 2.5, Maya 3.0, and Maya 4.0. Exporting from other versions of Max may require a re-build of the source against the version of the Max SDK you are using.

The DirectX SDK includes a DOS utility called CONV3DS.EXE which can be used to export basic mesh data from .3ds files to .x files. However, functionality is limited, and is not recommended for production work.

Tutorial on using the SDK exporter with 3dsmax to create .x files:
http://www.mvps.org/vbdx/tutorials/exportx/

Free Windows front-end for DOS conversion tools:
http://www.mvps.org/vbdx/downloads/

          --------------------------
22.2: How do I create compressed textures?

The SDK comes with a tool called the 'DirectX Texture Tool' which can be used to create .dds files. NVIDIA offers a great plugin for Photoshop on their developer relations web site that allows you to open and save .dds files.

http://developer.nvidia.com

          --------------------------
22.3: Where can I find free 3d models and textures?

Free stuff can be found here:

http://www.3dcafe.com
http://avalon.viewpoint.com/
http://www.grsites.com/textures/


Hit Counter